2016-04-07 30 views
0

列出我有以下代碼哈斯克爾加入列表


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

我失去的是什麼?

+0

後完整的錯誤。 – chi

+0

@chi在問題上增加了錯誤 – taivo

回答

1

groupEq聲明爲返回[[a]],但((last acc) ++ [x])的類型爲[a]。 一個快速和骯髒的解決方案是將此表達式更改爲 init acC++ [last acC++ [x]]

+0

@bipill是的,你確實是對的。但我想知道爲什麼在開始時將累加器設置爲[[]]沒有幫助。那麼不會是'((last acc)++ [x])''[[a]]'類型嗎? – taivo

+0

絕對不是。 'last [[]]'是'[]',它的類型是'[a]'。 – bipll