为什么这个函数的 pointfree 版本看起来像这样?
我一直在使用 Haskell,包括练习以无点形式编写函数。这是一个示例函数:
dotProduct :: (Num a) => [a] -> [a] -> a
dotProduct xs ys = sum (zipWith (*) xs ys)
我想以无点形式编写这个函数。这是我在其他地方找到的一个例子:
dotProduct = (sum .) . zipWith (*)
但是,我不明白为什么无点形式看起来像 (sum .) 。 zipWith (*)
而不是 sum 。 zipWith (*)
.为什么 sum 放在括号中并且有 2 个复合运算符?
I've been playing around with Haskell a fair bit, including practising writing functions in point-free form. Here is an example function:
dotProduct :: (Num a) => [a] -> [a] -> a
dotProduct xs ys = sum (zipWith (*) xs ys)
I would like to write this function in point-free form. Here is an example I found elsewhere:
dotProduct = (sum .) . zipWith (*)
However, I don't understand why the point-free form looks like (sum .) . zipWith (*)
instead of sum . zipWith (*)
. Why is sum in brackets and have 2 composition operators?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
KennyTM 的答案非常好,但我仍然想提供另一种观点:
(.) f g
在给定的g
的结果上应用f
参数(.) (.) (.) f g
将f
应用于给定两个参数(.) (.)
g
的结果g
的结果上应用f
( .~) = (.) (.) (.)
,(.~~) = (.) (.) (.~)
,(.~~~ ) = (.) (.) (.~~)
现在let foo abcd = [1..5]; (.~~~) sum foo 0 0 0 0
结果为15
。TypeCompose
提供了(.)
的同义词,称为result
。也许这个名字更有助于理解正在发生的事情。如果导入相关实例(
import Control.Applicative
就可以),fmap
也可以代替(.)
,但它的类型更笼统,因此可能更令人困惑。KennyTM's answer is excellent, but still I'd like to offer another perspective:
(.) f g
appliesf
on the result ofg
given one argument(.) (.) (.) f g
appliesf
on the result ofg
given two arguments(.) (.) ((.) (.) (.)) f g
appliesf
on the result ofg
given three arguments(.~) = (.) (.) (.)
,(.~~) = (.) (.) (.~)
,(.~~~) = (.) (.) (.~~)
and nowlet foo a b c d = [1..5]; (.~~~) sum foo 0 0 0 0
results in15
.TypeCompose
provides a synonym for(.)
calledresult
. Perhaps this name is more helpful for understanding what's going on.fmap
also works instead of(.)
, if importing the relevant instances (import Control.Applicative
would do it) but its type is more general and thus perhaps more confusing.(sum .)
是一个部分。它被定义为任何二元运算符都可以这样写,例如
map (7 -) [1,2,3] == [7-1, 7-2, 7-3]
。The
(sum .)
is a section. It is defined asAny binary operators can be written like this, e.g.
map (7 -) [1,2,3] == [7-1, 7-2, 7-3]
.