【问题标题】:Haskell currying to remove argument variable at the endHaskell currying 在最后删除参数变量
【发布时间】:2013-09-25 13:33:23
【问题描述】:

我是一个尝试学习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 function-composition pointfree


    【解决方案1】:

    $ 在 Haskell 中定义为

    f $ x = f x
    infixr 0 $
    

    因此,如果您扩展代码的第一个 sn-p,

    map sum $ transpose x
    

    变成

    map sum (transpose x)
    

    这会起作用。

    但是第二个sn-p

    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)
    

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

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

    【讨论】:

    • 我将补充一点,删除参数时的一般经验法则是将您的 $s 更改为 .s。显然这并不适用于所有情况,但是对于模式f x = g1 $ g2 $ g3 $ g4 x,您可以将其重写为f = g1 . g2 . g3 . g4
    【解决方案2】:

    正确的代码是:

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

    如何到达?记住以下两条规则:

    f $ x = f x
    f. g $ x == (f.g) x == f (g x) == f $ g x
    

    因此,

    addPoly  x = map sum $ transpose x
    

    改写为

    addPoly  x = map sum $ transpose $ x
    

    然后每个$,但最后一个被.替换。

    addPoly  x = map sum . transpose $ x
    

    现在,由于您只有一个$,并且参数仅在$ 的右侧,您可以切换到无点样式

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      • 2020-09-25
      • 2013-09-25
      相关资源
      最近更新 更多