Eq => function in Haskell

后端 未结 2 1881
迷失自我
迷失自我 2021-01-28 13:25

I am trying to figure out how to write this function with the Eq function in Haskell.

An easy function that I am trying to implement is:

f :: Eq a =>          


        
相关标签:
2条回答
  • 2021-01-28 13:57

    You can also use span and a recursive call to make it work:

    f :: Eq a => [a] -> [[a]]
    f [] = []
    f l@(x:xs) = grouped : f remainder
        where
            (grouped, remainder) = span (== x) l
    

    Here you have the live example

    0 讨论(0)
  • 2021-01-28 14:03

    The presence of the Eq typeclass in your type is a red herring: it is not related to the error you report. The error you report happens because you have defined how the function should behave when the list is empty (f [] =) and when the list has at least two elements (f (x:x':xs) =), but not when the list has exactly one element. The solution will be to add a case that begins*

    f [x] = ????
    

    and decide how to deal with one-element lists. Or to find some other way to write the function that deals with all of its cases.


    * Note that f [x] is the same thing as f (x:[]).

    0 讨论(0)
提交回复
热议问题