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

标签 function haskell

在 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/

相关文章:

c - c中函数内的函数引用

javascript - 数组中函数的用途?

javascript - 在node.js中调用和指定自定义命令?这可能吗

python - 在函数中返回一个列表。另外,还有 while 循环的问题

haskell - 忽略 Haskell Aeson 输入中的 JSON 字段

haskell - 如何在元组列表中查找重复项?

r - Magrittr 函数 - 如何打包它们?

function - 在 GHCi 中,为什么函数箭头 `:kind (->)` 的类型包含问号 `(->)::?? -> ? -> *` ?

haskell - 如何将 Float 小数部分的前 32 位转换为 Word32?

algorithm - 我可以在红黑树中插入未排序的数据吗?