gpt4 book ai didi

Haskell 柯里化(Currying)以删除最后的参数变量

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

我是一个试图学习haskell的新手,我尝试在其他论坛中搜索类似的内容,但找不到类似的问题。

addPoly :: (Num a)=>[[a]]->[a]
addPoly x = map sum $ transpose x

运行良好

但是当我最后删除 x 时,它会出错

addPoly :: (Num a)=>[[a]]->[a]
addPoly = map sum $ transpose

错误提示:

Couldn't match expected type `[[Integer]] -> [Integer]'
with actual type `[Integer]'
In the expression: map sum $ transpose
In an equation for `addPoly': addPoly = map sum $ transpose

Couldn't match expected type `[[Integer]]'
with actual type `[[a0]] -> [[a0]]'
In the second argument of `($)', namely `transpose'
In the expression: map sum $ transpose
In an equation for `addPoly': addPoly = map sum $ transpose

无法弄清楚我在这里缺少什么。

免责声明:这不是作业问题

最佳答案

$ 在 Haskell 中定义为

f $ x = f x
infixr 0 $

因此,如果您展开代码的第一个片段,

map sum $ transpose x

变成了

map sum (transpose x)

这会起作用。

但是第二个片段

map sum $ transpose 

变成了

map sum transpose

当你用x调用它时,你会得到

map sum transpose x

它实际上将 sum 映射到 transpose (并使用参数 x 调用结果,这也没有意义,并导致您收到的错误消息,因为 map 将返回 List,而不是函数),而不是通过 transpose x

为此,您需要使用 . 函数,而不是 $,其定义为

(.) f g = \x -> f (g x)

如果你这样做,你的代码

map sum . transpose

变成了

\x -> map sum (transpose x)

当你从某个参数x调用它时,它就变成了

map sum (transpose x)

这是我们开始使用的(正确的)代码。

如果有不清楚的地方,请告诉我。

关于Haskell 柯里化(Currying)以删除最后的参数变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19006400/

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