[英]Haskell - Group list elements with foldr function
這是在Haskell中的一個賦值。 我們的任務是使用foldr函數定義各種函數。
我們得到了一個類型:
group :: Eq a => [a] -> [[a]]
並被要求定義它:
group [1,2,2,3,4,4,4,5] = [[1], [2,2], [3], [4,4,4], [5]]
group [1,2,2,3,4,4,4,5,1,1,1] = [[1], [2,2], [3], [4,4,4], [5], [1,1,1]]
這是我到目前為止:
group = foldr (\x xs -> if x == head (head xs) then (x : head xs) : xs else (x : []) : (head xs) : xs )
但是當我嘗試將其加載到ghci解釋器時,我收到以下錯誤消息:
Couldn't match type `[a0] -> [a]' with `[[a]]'
Expected type: [a] -> [[a]]
Actual type: [a] -> [a0] -> [a]
In the return type of a call of `foldr'
Probable cause: `foldr' is applied to too few arguments
In the expression:
foldr
(\ x xs
-> if x == head (head xs) then
(x : head xs) : xs
else
(x : []) : (head xs) : xs)
In an equation for `group':
group
= foldr
(\ x xs
-> if x == head (head xs) then
(x : head xs) : xs
else
(x : []) : (head xs) : xs)
如果有人能解釋為什么我的代碼沒有像我期望的那樣工作的原因,那將非常感激。 謝謝。
我認為你走在正確的軌道上,所以我會試着把你的想法寫得更好一些。 我想說的是:你應該將foldr
的第一個參數拉出一個函數並再次進行模式匹配:
group :: Eq a => [a] -> [[a]]
group = foldr f undefined
where f x [] = undefined
f x (ys@(y:_):yss)
| x == y = undefined
| otherwise = undefined
這應該做 - 現在你只需要放入正確的東西,我把undefined
:)
我會稍后回來完成它
好吧我猜你放棄了什么 - 無論如何這里有一個解決方案:
group :: Eq a => [a] -> [[a]]
group = foldr f []
where f x [] = [[x]]
f x (ys@(y:_):yss)
| x == y = (x:ys):yss
| otherwise = [x]:ys:yss
以及一些例子:
λ> group []
[]
λ> group [1]
[[1]]
λ> group [1,1]
[[1,1]]
λ> group [1,2,1]
[[1],[2],[1]]
λ> group [1,2,2,3,4,4,4,5]
[[1],[2,2],[3],[4,4,4],[5]]
請注意, f
s模式並非詳盡無遺(這是沒有問題的 - 想想為什么) - 當然,如果你願意,你可以擴展它(如果你不同意你的group [] = []
。
只是要提一下,如果我沒有錯,這就是99個haskell問題中的問題9,可以在這里找到: https : //wiki.haskell.org/99_questions/
對於每個問題,它都有一堆解決方案(通常),因為Carsten提供了一個很好的解決方案,你可以去那里看看其他解決方案,這樣你就可以通過各種方式獲得不同的想法!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.