如何在 Haskell 中使用 curried 函数与地图?
How to use curried functions in Haskell with map?
尝试通过重新定义前奏函数来学习如何使用折叠:
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?任何帮助将不胜感激。
您混淆了函数应用程序和组合。这有帮助吗?
all :: (a -> Bool) -> [a] -> Bool
all fn = and . (map fn)
实际上,这等同于您的代码 + 来自@Carcigenicate 的评论
尝试通过重新定义前奏函数来学习如何使用折叠:
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?任何帮助将不胜感激。
您混淆了函数应用程序和组合。这有帮助吗?
all :: (a -> Bool) -> [a] -> Bool
all fn = and . (map fn)
实际上,这等同于您的代码 + 来自@Carcigenicate 的评论