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 =>
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
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:[])
.