這是一個練習:
-- Implement the function sumRights which sums all Right and discard Left
-- Examples:
-- sumRights [Right 1, Left "bad value", Right 2] ==> 3
-- sumRights [Left "bad!", Left "missing"] ==> 0
我的想法是,作為第一步,將帶有 map 的串列轉換為僅包含整數的串列。我寫了以下內容:
transformListToInt :: [Either a Int] -> Int
transformListToInt list = map f list
where f (Right b) = b
f (Left c) = 0
但它給了我以下錯誤:
* Couldn't match expected type `Int' with actual type `[a]'
* In the expression: map f list
In an equation for `sumRights':
sumRights list
= map f list
where
f (Right b) = b
f (Left c) = c
有人能幫我理解為什么我會收到這個錯誤嗎?(最初的問題不是那么重要,我可以用不同的方式解決)
uj5u.com熱心網友回復:
你最后忘了總結串列:
transformListToInt :: [Either a Int] -> Int
transformListToInt list = sum $ map f list
where f (Right b) = b
f (Left c) = 0
撰寫相同內容的更短方法是:
transformListToInt = sum . map (fromRight 0)
甚至更短:
transformListToInt = sum . rights
(兩種方式都需要匯入Data.Either)
uj5u.com熱心網友回復:
map將一個串列[x0,x1,...]變成另一個串列[f x0, f x1, ...]。它不能產生Int你的型別宣告,所以編譯器抱怨。
由于您map生成了一個 type 值[Int],您需要將該串列轉換為其元素的總和(使用sum)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/366335.html
標籤:哈斯克尔
上一篇:將串列分成子串列:將相同的值添加到一個子串列中,將不同的值添加到另一個子串列中
下一篇:交換元組串列中的兩個元素
