使用占位符扩展3个列表

时间:2015-11-01 04:58:11

标签: scala functional-programming currying

Martin Odersky编写的Scala编程9.3显示了一个使用占位符_引用curried函数中的“second”函数的示例

enter image description here

enter image description here

说我有3个列表:

def curriedSum(x:Int)(y:Int)(z:Int) = x+y+z

我可以这么写

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

并访问像这样的中介

def f(x:Int) = ((y:Int) => ((z:Int) => x+y+z))
                                                  //> f: (x#582190: Int#1111)Int#1111 => (Int#1111 => Int#1111)
        val b = f(1)                      //> b  : Int#1111 => (Int#1111 => Int#1111) = <function1>
        val c = b(2)                      //> c  : Int#1111 => Int#1111 = <function1>
        c(3)                              //> res0: Int#1111 = 6 

但是如何使用占位符访问中间人(上面代码中的b和c)呢?是2个列表的情况?我能做的最好的就是

  def k = curriedSum(1)_                          //> k: => Int#1111 => (Int#1111 => Int#1111)
  k(2)(3)                                         //> res1: Int#1111 = 6

因为我跳过了一个中间人,所以不是很满意。如何用占位符恢复“第三”功能?

这是我想要实现的虚拟伪代码。

k = curriedSum(1)__
l = k(2)_
l(3)

2 个答案:

答案 0 :(得分:1)

我可以想到三种方法:

def k = curriedSum(1)_                    //> k: => Int => (Int => Int)

def l = k(2)(_)                           //> l: => Int => Int
l(3)                                      //> res0: Int = 6

def m = k(2)                              //> m: => Int => Int
m(3)                                      //> res1: Int = 6

def n = k.apply(2)                        //> n: => Int => Int
n(3)                                      //> res2: Int = 6    

理解多个参数列表和一个参数列表之间的区别是一件有趣的事情。

def l = curriedSum(1)(_: Int)(_: Int)           //> l: => (Int, Int) => Int
l(2,3)                                    //> res0: Int = 6
//l(2)(3) ERROR

def m = curriedSum(1)_                          //> m: => Int => (Int => Int)
//m(2,3)  ERROR
m(2)(3)                                   //> res1: Int = 6                

答案 1 :(得分:0)

你仍然可以这样做,语法略有不同:

scala> def l = k(2)(_)
l: Int => Int

scala> l(3)
res3: Int = 6