【问题标题】:What is the difference between multiple argument lists and returning a function?多个参数列表和返回函数有什么区别?
【发布时间】:2013-10-24 19:59:50
【问题描述】:

def f(x: Int)(y: Int) = x + ydef f(x: Int) = (y: Int) => x + y 有什么区别?

当我对前者和后者一视同仁时,REPL 似乎并不高兴:

scala> def f(x: Int)(y: Int) = x + y
f: (x: Int)(y: Int)Int

scala> f(42)
<console>:9: error: missing arguments for method f;
follow this method with `_' if you want to treat it as a partially applied function
              f(42)
               ^

scala> def f(x: Int) = (y: Int) => x + y
f: (x: Int)Int => Int

scala> f(42)
res2: Int => Int = <function1>

确切的区别是什么?我应该何时使用哪种形式?

【问题讨论】:

  • 嗯,一个是一个有两个参数的函数,一个返回一个接受一个参数的函数。没有?
  • 我喜欢想到的方式是,第一种方法是两个一元参数列表返回一个Int(所以f(0) 的结果仍然是一个方法(y: Int)Int),而后者是一种方法,其中一个一元 arglist 返回一个一元函数 Int =&gt; Int。这就解释了为什么只有前者抱怨缺少下划线; f(0) 在这种情况下不会计算为函数。

标签: function scala partial-application


【解决方案1】:

区别是

def f(x: Int)(y: Int) = x + y

是一个柯里化函数。具有两个参数列表的函数。您可以只使用一个参数,但您需要指定哪个参数。

f(42) _ // this is short for f(42)(_: Int)

将生成一个部分应用函数,其中x 的值为42。你也可以这样做:

f(_: Int)(42) // note: the first parameter must be used this way

这会将y 的值设置为42
仅使用几个参数调用柯里化函数将生成部分应用函数。

def f(x: Int) = (y: Int) => x + y

是部分应用函数。这里有一个函数,它接受一个参数并返回一个本身接受参数的函数。

【讨论】:

    【解决方案2】:

    使用第一种语法,您需要按照编译器的建议添加_

    scala> f(42) _
    res1: Int => Int = <function1>
    

    cf : Why and when do I need to follow a method name with _?

    【讨论】:

      猜你喜欢
      • 2011-10-11
      • 2014-02-23
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 2015-08-09
      • 2010-09-14
      相关资源
      最近更新 更多