gpt4 book ai didi

function - 与函数组合混淆

转载 作者:行者123 更新时间:2023-12-02 15:28:24 24 4
gpt4 key购买 nike

开始学习Haskell:

*Main> map double [1,2,3]
[2,4,6]

*Main> sum (map double [1,2,3])
12

*Main> (sum . map) (double) ([1,2,3])

<interactive>:71:8:
Couldn't match type ‘[b0] -> [b0]’ with ‘[[t0] -> t]’
Expected type: (b0 -> b0) -> [[t0] -> t]
Actual type: (b0 -> b0) -> [b0] -> [b0]
Relevant bindings include it :: t (bound at <interactive>:71:1)
Probable cause: ‘map’ is applied to too few arguments
In the second argument of ‘(.)’, namely ‘map’
In the expression: sum . map

根据这个答案:Haskell: difference between . (dot) and $ (dollar sign) “. 运算符的主要目的不是避免括号,而是链接函数。它可以让您将右侧出现的任何内容的输出与左侧出现的任何内容的输入联系起来。”。

好的,为什么我的示例不起作用?实际类型和预期类型不同,但为什么呢?毕竟,根据这个描述 map 应该在输入上采用 (double) ([1,2,3]) 并将其输出传递给 sum的输入?

最佳答案

原因是 . 只允许函数在传递给下一个参数之前采用 一个 参数。所以:

(sum . map) double [1,2,3]

将成为

(sum (map double)) [1,2,3]

...我们不能对一个函数求和,对吗?大量输入错误!

你要做的是:

(sum . map double) [1,2,3]

减少为:

sum (map double [1,2,3])

如果你想看,下面是 . 的定义:

(.) :: (b -> c) -> (a -> b) -> (a -> c)
(.) f g arg = f (g arg)

如果你真的很聪明,你可以双重组合一些东西,这样它在传递之前需要两个参数:

((sum .) . map) double [1,2,3]

减少为:

(sum . map double) [1,2,3]

最后:

sum (map double [1,2,3])

关于function - 与函数组合混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29174842/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com