【发布时间】:2014-02-11 02:10:09
【问题描述】:
仅作背景介绍我是 Haskell 和 FP 初学者,自学。
我在Learn You a Haskell for great good 上经历了折叠。
在这个我遇到了这个功能
map' :: (a -> b) -> [a] -> [b]
map' f xs = foldr (\x acc -> f x : acc) [] xs
一切都很好,但据我了解,lambda x 的第一个参数与[] 匹配,第二个acc 与xs 匹配。正确的?混乱始于作者说Then, we prepend it to the accumulator, which is was []. 第二个参数acc 与[] 是第一个参数如何匹配?没有意义。
但他的实现正在运行,而我的(将 [] 和 xs 互换为参数)给出了一个很大的错误
Practice.hs:88:41:
Couldn't match type `a' with `b'
`a' is a rigid type variable bound by
the type signature for map' :: (a -> b) -> [a] -> [b]
at Practice.hs:87:9
`b' is a rigid type variable bound by
the type signature for map' :: (a -> b) -> [a] -> [b]
at Practice.hs:87:9
Expected type: [b]
Actual type: [a]
In the second argument of `foldr', namely `xs'
In the expression: foldr (\ x acc -> f x : acc) xs []
In an equation for map':
map' f xs = foldr (\ x acc -> f x : acc) xs []
Failed, modules loaded: none.
我在这里缺少什么? foldr 在内部使用 flip 吗?还是我完全理解错了?
【问题讨论】:
-
嗯,我不确定您所说的“匹配”是什么意思。最终,在您的示例中,给定函数在其 second 参数中使用
[]调用。 -
lambda 不适用于
[]和xs。相反,它是foldr的第一个参数。foldr的第二个和第三个参数分别是[]和xs。 -
@DavidYoung 我的意思是,在我看来,第一个参数(到 lambda)对应于第一个参数(
[]),就像在命令式编程中一样。我忘记了 lambda 也是foldr的一个参数以及其他 2 个参数。并且由foldr将其应用于其他两个参数。就像@TomEllis 说的那样。 -
@TomEllis 您应该将该评论作为答案。这是我忽略的主要问题,导致了这个问题。
-
好的,我已经回答了。