`
bit1129
  • 浏览: 1051522 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

【Scala十三】Scala核心七:部分应用函数

 
阅读更多

何为部分应用函数?

Partially applied function: A function that’s used in an expression and that misses some of its arguments.
For instance, if function f has type Int => Int => Int, then f and f(1) are partially applied functions.

 

A partially applied function is an expression in which you don’t supply all of the arguments needed by the function. Instead, you supply some, or none, of the needed arguments.

缺失的是函数需要的参数

 

 

 

将函数应用(apply)于方法:

In Scala, when you invoke a function, passing in any needed arguments, you apply that function to the arguments

 

 

package spark.examples.scala.partialapplyfunc


object PartialApplyFuncTest {

  def calc(a: Int, b: Int, c: Int) = a + b - c

  def main(args: Array[String]) {
    val list = List(1, 2, 3, 4, 5)
    list.foreach(println _) //缺失所有参数(因为println函数只有一个参数,因此println _所有参数等价于println(_)缺失一个参数)
    list.foreach(println(_)) //缺失一个参数(println实际上就一个参数)
    // list.foreach(println _)等价于list.foreach(x => println x)
    // list.foreach(println(_)),是否等价于list.foreach(println _)?等价

    val print = println(_: Int) //声明时,需要为缺失的参数指定类型,上面不需要是因为可以从list中推导出来
    list.foreach(print)

    //如下通过_定义的部分应用函数,必须为_指定类型
    //val s0 = calc //编译错,参数个数缺失或者根本不存在无参的calc函数
    val s00 = calc(1,2,4) //参数足够,直接调用
    val s1 = calc(_: Int, 2, 3) //缺失第一个参数
    val s2 = calc(_: Int, _: Int, 3) //缺失第一个,第二个参数
    val s3 = calc(_: Int, 2, _: Int) //缺失第一个,第二个参数
    val s4 = calc(_: Int, _: Int, _: Int) //缺失第一个,第二个和第三个参数
    val s5 = calc _ //所有的参数列表都缺失(缺失第一个,第二个和第三个参数)
    println(s1(10))
    println(s2(20, 30))
    println(s3(10, 20))
    println(s4(3, 2, 1))
    println(s5(1, 3, 5))

    //apply语法,s5(1,3,5)等价于s5.apply(1,3,5),apply方法将参数列表发送给s5指向的函数,进行调用

    val f = (_: Int) + (_: Int)
    println(f(1, 2))
  }
}

 

 问题:

定义val s1 = calc(_:Int, 2,3)时为什么一定要为缺失的参数指定类型,而val s5 = calc _则不需要?因为calc的第一个参数类型是确定的,为什么这里还需要再给定类型?

 

scala>   def calc(a: Int, b: Int, c: Int) = a + b - c
calc: (a: Int, b: Int, c: Int)Int

scala> calc _
res5: (Int, Int, Int) => Int = <function3>

scala> calc(1,2,_)
<console>:9: error: missing parameter type for expanded function ((x$1) => calc(1, 2, x$1))
              calc(1,2,_)
                       ^

scala> calc(1,2,_:Int)
res7: Int => Int = <function1>

scala>

 

 

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics