【问题标题】:Missing parameter type for expanded function with underscore带有下划线的扩展函数缺少参数类型
【发布时间】:2017-09-25 21:26:01
【问题描述】:

我正在尝试制作自己组合的功能 -

def genericComposition[T](f: T => T, g: T => T) = {
    def call(x: T) = g(f(x))
    call _
}

def testComposition[T](g: T=>T, n: Int) = {
  val call = genericComposition[T](g,g)
  def helper(res: T, m: Int) : T = {
    if(m == 0) res
    else helper(call(res), dec(m))
  }
  helper(_,n)
}

这应该调用 f 与 f (f(f(x)) n 次的组合,非通用版本,其中所有 T 都是 Int 或 Double 等工作正常,但是当我尝试制作通用版本时,我使用下划线将 x 作为参数传递给辅助函数,但出现错误:

错误:(26, 11) 缺少扩展函数的参数类型 ((x$1: ) => 助手(x$1, n)) 助手(_,n)

     ^

【问题讨论】:

    标签: scala functional-programming


    【解决方案1】:

    根据我的经验,_ 语法糖有点挑剔。 Scala 的类型推断并不完美。它适用于简单的情况,但在一些更微妙的情况下,有时您必须自己为其提供类型信息。也许其他人可以解释为什么会出现这种情况。

    如果您指定函数的返回类型,它可以解决问题。无论如何,这通常被认为是好的风格:

    def testComposition[T](g: T=>T, n: Int): T => T = {
      ...
      helper(_,n)
    }
    

    【讨论】:

      【解决方案2】:

      请检查是否是您需要的

      def testComposition[T](g: T=>T, n: Int) = {
        val call = genericComposition[T](g,g)
        def helper( m: Int,res: T) : T = { //changed order of parameters
          if(m == 0) res
          else helper(dec(m),call(res))
        }
        (helper _).curried(n)             // now we can make it carried 
      }
      
      println(testComposition[Int](x=>x+1,5)(5))
      

      【讨论】:

        猜你喜欢
        • 2011-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多