7

在发现柯里化多参数组方法是可能的之后,我试图获得一个需要隐式参数的部分应用函数。

似乎不可能这样做。如果不是,你能解释一下为什么吗?

scala> def sum(a: Int)(implicit b: Int): Int = { a+b }
sum: (a: Int)(implicit b: Int)Int

scala> sum(3)(4)
res12: Int = 7

scala> val partFunc2 = sum _
<console>:8: error: could not find implicit value for parameter b: Int
       val partFunc2 = sum _
                       ^

我使用一个单例对象来创建这个部分应用的函数,并且我想在定义了隐式 int 的范围内使用它。

4

2 回答 2

8

那是因为您在范围内没有隐式 Int 。看:

scala> def foo(x: Int)(implicit y: Int) = x + y
foo: (x: Int)(implicit y: Int)Int

scala> foo _
<console>:9: error: could not find implicit value for parameter y: Int
              foo _
              ^

scala> implicit val b = 2
b: Int = 2

scala> foo _
res1: Int => Int = <function1>

编译器将隐式替换为实际值。如果您对方法进行 curry,结果是一个函数,并且函数不能有隐式参数,因此编译器必须在您对方法进行 curry 时插入该值。

编辑:

对于您的用例,为什么不尝试以下方法:

object Foo {
  def partialSum(implicit x: Int) = sum(3)(x)
}
于 2012-06-04T13:29:18.803 回答
0
scala> object MySingleton {
 |   def sum(a: Int)(implicit b: Int): Int = { a+b }
 |  
 |
 |   def caller(a: Int) =  {
 |     implicit val b = 3; // This allows you to define the partial below
 |     def pf = sum _      // and call sum()() without repeating the arg list. 
 |     pf.apply(a)
 |   }
 | } 
defined module MySingleton


scala> MySingleton.caller(10)
res10: Int = 13
于 2014-07-19T06:27:31.507 回答