gpt4 book ai didi

function - 将 2 个参数传递给 Haskell 中的函数

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

在 Haskell 中,我知道如果我定义这样的函数 add x y = x + y
然后我像这样调用add e1 e2。该调用相当于 (add e1) e2
这意味着将 add 应用于一个参数 e1 会生成一个新函数,然后将该函数应用于第二个参数 e2

这就是我在 Haskell 中不明白的地方。在其他语言(如 Dart)中,要完成上述任务,我会这样做

add(x) {
return (y) => x + y;
}

我必须显式返回一个函数。那么“产生一个新函数,然后应用于第二个参数”的部分是否会自动在 Haskell 中进行底层操作?如果是这样,那个“隐藏”功能是什么样的?或者我只是误解了 Haskell?

最佳答案

在 Haskell 中,一切都是值,

add x y = x + y

只是以下语法糖:

add = \x -> \y -> x + y

了解更多信息:https://wiki.haskell.org/Currying :

In Haskell, all functions are considered curried: That is, all functions > in Haskell take just single arguments.

This is mostly hidden in notation, and so may not be apparent to a new Haskeller. Let's take the function

div :: Int -> Int -> Int

which performs integer division. The expression div 11 2 unsurprisingly evaluates to 5. But there's more that's going on than immediately meets the untrained eye. It's a two-part process. First,

div 11

is evaluated and returns a function of type

Int -> Int

Then that resulting function is applied to the value 2, and yields 5. You'll notice that the notation for types reflects this: you can read

Int -> Int -> Int

incorrectly as "takes two Ints and returns an Int", but what it's really saying is "takes an Int and returns something of the type Int -> Int" -- that is, it returns a function that takes an Int and returns an Int. (One can write the type as Int x Int -> Int if you really mean the former -- but since all functions in Haskell are curried, that's not legal Haskell. Alternatively, using tuples, you can write (Int, Int) -> Int, but keep in mind that the tuple constructor (,) itself can be curried.)

关于function - 将 2 个参数传递给 Haskell 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28249389/

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