2017-01-02 20 views
0

努力学习如何通过重新定义序幕功能使用的折叠:如何在地图中使用Haskell中的curried函数?

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]匹配任何列表,甚至是空的列表?为什么我可以在不包含列表但不包含地图的情况下咖喱foldr?任何帮助,将不胜感激。

+1

你的最后一个错误是因为'[XS]'将只与一个元素匹配列表中的注释。只需从参数和参数中去除“地图”的方括号即可。 – Carcigenicate

+3

Downvoter应该评论,因为答案或问题都不是那么糟糕。 – Carcigenicate

+0

@Carcigenicate啊谢谢你有道理 – user6731064

回答

2

您将功能应用程序与构图混合在一起。这有帮助吗?

all :: (a -> Bool) -> [a] -> Bool 
all fn = and . (map fn) 

在实践中,这等同于你的代码+从@Carcigenicate

+0

没有投票,但我认为那些曾经希望你解释'功能全部错误的非穷举模式'的人。 – Alec

+1

@Simon H非常感谢你,显然我需要重新编写组合和应用程序 – user6731064

+0

注意:你确实需要有'fn'参数:'all =和。地图'很好。 – Bakuriu