简体   繁体   English

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

[英]passing 2 arguments to a function in Haskell

In Haskell, I know that if I define a function like this add xy = x + y 在Haskell中,我知道如果我定义这样的函数,则add xy = x + y
then I call like this add e1 e2 . 然后我这样称之为add e1 e2 that call is equivalent to (add e1) e2 该调用等同于(add e1) e2
which means that applying add to one argument e1 yields a new function which is then applied to the second argument e2 . 这意味着将add到一个参数e1产生一个新函数,然后将其应用于第二个参数e2

That's what I don't understand in Haskell. 这就是我在Haskell中无法理解的。 in other languages (like Dart), to do the task above, I would do this 在其他语言(如Dart)中,为了完成上述任务,我会这样做

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

I have to explicitly return a function. 我必须显式return一个函数。 So does the part "yields a new function which is then applied to the second argument" automatically do underlying in Haskell? 那么“产生一个新函数然后应用于第二个参数”的部分是否会在Haskell中自动执行? If so, what does that "hiding" function look like? 如果是这样,那个“隐藏”功能是什么样的? Or I just missunderstand Haskell? 或者我只是想念哈斯克尔?

In Haskell, everything is a value, 在Haskell中,一切都是价值,

add x y = x + y

is just a syntactic sugar of: 只是一个语法糖:

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

For more information: https://wiki.haskell.org/Currying : 有关更多信息: https//wiki.haskell.org/Currying

In Haskell, all functions are considered curried: That is, all functions > in Haskell take just single arguments. 在Haskell中,所有函数都被认为是curry:也就是说,Haskell中的所有函数>只接受单个参数。

This is mostly hidden in notation, and so may not be apparent to a new Haskeller. 这主要隐藏在符号中,因此对于新的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. 表达式div 2 2毫不奇怪地评估为5.但是还有更多的事情发生,而不是立刻遇到未经训练的眼睛。 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 然后,结果函数应用于值2,并产生5.您会注意到类型的表示法反映了这一点:您可以阅读

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. 错误地称为“接受两个Ints并返回一个Int”,但它真正说的是“接受一个I​​nt并返回Int - > Int类型的东西” - 也就是说,它返回一个接受Int并返回一个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.) (可以将类型写为Int x Int - > Int,如果你真的是指前者 - 但由于Haskell中的所有函数都是curry,那不是合法的Haskell。或者,使用元组,你可以写(Int,Int) - > Int,但请记住,元组构造函数(,)本身可以用于curry。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM