【问题标题】:Scala, Currying on multi parameter-group method including implicit params?Scala,Currying 多参数组方法,包括隐式参数?
【发布时间】:2012-06-04 12:32:48
【问题描述】:

在发现currying multi parameter-groups method is possible 之后,我试图获得一个需要隐式参数的部分应用函数。

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

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 的范围内使用它。

【问题讨论】:

    标签: scala currying


    【解决方案1】:

    那是因为您在范围内没有隐式 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)
    }
    

    【讨论】:

    • 谢谢。但正如我所说,我需要在另一个单例对象中声明这个函数。我需要在我使用它的上下文中声明它。
    • 编辑了我的帖子。由于我已经提到的原因,我认为没有其他方法可以做到这一点。
    • 你是对的。由于柯里化给出 Function 和 Function 不允许隐式参数,我需要明确列出两组之一的参数。
    【解决方案2】:
    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
    

    【讨论】:

    • 欢迎来到 SO!请考虑留下一些直观的解释,而不仅仅是发布代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多