gpt4 book ai didi

haskell - 围绕何时撰写以及何时使用 $ 的困惑

转载 作者:行者123 更新时间:2023-12-02 05:56:35 25 4
gpt4 key购买 nike

returnGreater :: (Ord a) => a -> a -> a
returnGreater a b
| (a > b) = a
| otherwise = b

returnGreatest2 :: (Ord a, Num a) => a -> a -> a -> (a, a)
returnGreatest2 a b c
| (a > b) = (a, returnGreater b c)
| otherwise = (b, returnGreater a c)

sumOfSquares :: (Num a) => (a, a) -> a
sumOfSquares (a, b) = a^2 + b^2

鉴于上述功能,我很困惑为什么 让 x = sumOfSquares 。 returnGreatest2 返回

<interactive>:13:24: error:
• Couldn't match type ‘a -> a -> (a, a)’ with ‘(c, c)’
Expected type: a -> (c, c)
Actual type: a -> a -> a -> (a, a)
• Probable cause: ‘returnGreatest2’ is applied to too few arguments
In the second argument of ‘(.)’, namely ‘returnGreatest2’
In the expression: sumOfSquares . returnGreatest2
In an equation for ‘x’: x = sumOfSquares . returnGreatest2
• Relevant bindings include
x :: a -> c (bound at <interactive>:13:5)

但是 sumOfSquares $ returnGreatest2 3 5 7 做对了。由于 returnGreatest2 的类型与 sumOfSquares 预期的类型相同,我认为我能够组合它们。

最佳答案

组合和柯里化(Currying)可能有点令人困惑。 平方和。 returnGreatest2\x -> sumOfSquares (returnGreatest2 x)相同,但是returnGreatest2 x的类型是(Ord a, Num a) => a -> a -> (a, a)。在最终获得 (Ord a, Num a) => (a, a) 可接受的 类型的值之前,您需要传递所有 预期参数平方和

另一方面,sumOfSquares $ returnGreatest2 3 5 7 的解析方式与 sumOfSquares $ (returnGreatest2 3 5 7) 相同; ($) 运算符的优先级低于函数应用程序(或任何其他运算符)。

要真正组合这两个函数,您需要多层组合:

let f = ((sumOfSquares .) . ) . returnGreatest2

关于haskell - 围绕何时撰写以及何时使用 $ 的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53324778/

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