Haskell添加到列表中的列表

时间:2016-04-07 20:57:24

标签: haskell

我有以下代码


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

现在,我很难理解为什么它不会编译。 问题在于((last acc) ++ [x])部分。我理解它,因为它需要累加器的最后一个元素,此时它将[[a]]并尝试向其添加元素。

我想要实现的目标是: -- groupEq [1,2,2,3,3,3,4,1,1] ==> [[1], [2,2], [3,3,3], [4], [1,1]]

完整错误


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)’

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

groupEq被声明为返回[[a]],但((last acc) ++ [x])的类型为[a]。 快速而肮脏的解决方案是将此表达式更改为 init acc ++ [last acc ++ [x]]