【发布时间】:2017-05-16 19:15:20
【问题描述】:
尝试通过重新定义前奏函数来学习如何使用折叠:
import Prelude hiding (sum, product, length, and, or, all, any, filter)
到目前为止,我已经完成了所有工作,但我无法弄清楚我做错了什么。我是这样定义的:
and :: [Bool] -> Bool
and = foldr (&&) True
...
all :: (a -> Bool) -> [a] -> Bool
all = and $ map
但这会显示一条错误消息:
Probable cause: ‘map’ is applied to too few arguments
我也尝试将其定义为:
and :: [Bool] -> Bool
and = foldr (&&) True
...
all :: (a -> Bool) -> [a] -> Bool
all f [xs] = and $ map f [xs]
这编译得很好,但是当我尝试调用它时,它会说:
[1 of 1] Compiling Fold ( Fold.hs, interpreted )
Ok, modules loaded: Fold.
*Fold> all even [0,2,4,6]
*** Exception: Fold.hs:17:1-29: Non-exhaustive patterns in function all
我不明白,因为 [xs] 不应该匹配任何列表,即使是空列表?为什么我可以curry foldr而不包括列表而不包括地图?任何帮助将不胜感激。
【问题讨论】:
-
您的最后一个错误是因为
[xs]只会匹配具有单个元素的列表。只需从参数和map的参数中删除方括号。 -
反对者应该发表评论,因为答案或问题都不是那么糟糕。
-
@Carcigenicate 啊谢谢你说得通
-
@Carcigenicate 我认为这个问题也不值得一票否决,但这不是我的要求,也不是你的要求。人们可以按自己喜欢的方式投票,没有义务在 cmets 中解释原因。
-
@amalloy 不过,解释否决票是一种很好的礼仪;尤其是当 OP 只有 8 个代表并且可能不知道他们做错了什么时。没有必要,不,但对不熟悉该网站的人肯定有帮助。
标签: haskell functional-programming currying