taivo
taivo

Reputation: 139

Haskell add to list in list

i have the following code


groupEq :: Eq a => [a] -> [[a]]
groupEq list = foldl (\acc x -> if (isType acc x) then ((last acc) ++ [x]) else acc++[[x]]) [] list

isType :: Eq a => [[a]] -> a -> Bool
isType list item 
    | (length list) == 0 = False
    | head (last list) == item = True
    | otherwise = False

Now, i am having difficulties understanding why it would not compile. The problem is with the ((last acc) ++ [x]) part of it. I understand it as it takes the last element of accumulator, which would be [[a]] at this point and tries to add an element to it.

The idea what i want to achieve is this: -- groupEq [1,2,2,3,3,3,4,1,1] ==> [[1], [2,2], [3,3,3], [4], [1,1]]

Full error is


Couldn't match type ‘a’ with ‘[a]’
      ‘a’ is a rigid type variable bound by
          the type signature for groupEq :: Eq a => [a] -> [[a]]
          at exam_revisited.hs:3:12
    Expected type: [[[a]]]
      Actual type: [[a]]
    Relevant bindings include
      x :: a (bound at exam_revisited.hs:4:28)
      acc :: [[a]] (bound at exam_revisited.hs:4:24)
      list :: [a] (bound at exam_revisited.hs:4:9)
      groupEq :: [a] -> [[a]] (bound at exam_revisited.hs:4:1)
    In the first argument of ‘last’, namely ‘acc’
    In the first argument of ‘(++)’, namely ‘(last acc)’

What am i missing here?

Upvotes: 0

Views: 81

Answers (1)

bipll
bipll

Reputation: 11940

groupEq is declared to return [[a]], but ((last acc) ++ [x]) is of type [a]. A quick and dirty solution is to change this expression into init acc ++ [last acc ++ [x]].

Upvotes: 1

Related Questions