简体   繁体   English

带下划线的扩展功能缺少参数类型

[英]Missing parameter type for expanded function with underscore

I'm trying to make function that compose itself - 我正在尝试使功能自行组合-

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)
}

This should call composition of f with f (f(f(x)) n times, non generic version, where all T's are Int or Double, etc works fine, but when I try to make generic version I use underscore to pass x as parameter to the helper function, but have error: 这应该用f(f(f(f(x)))调用f的组合n次,非通用版本,其中所有T均为Int或Double,等等工作正常,但是当我尝试制作通用版本时,我使用下划线传递x参数到辅助函数,但有错误:

Error:(26, 11) missing parameter type for expanded function ((x$1: ) => helper(x$1, n)) helper(_,n) 错误:(26,11)缺少扩展功能的参数类型((x $ 1:)=> helper(x $ 1,n))helper(_,n)

  ^ 

In my experience, the _ syntactic sugar is a bit finicky. 以我的经验, _语法糖有点挑剔。 Scala's type inference is not perfect. Scala的类型推断并不完美。 It works in simple cases, but in some more subtle cases sometimes you have to provide it with type information yourself. 它在简单情况下有效,但在某些更微妙的情况下,有时您必须自己为其提供类型信息。 Perhaps someone else can explain why that's the case here. 也许其他人可以解释为什么是这种情况。

If you specify the return type of your function, it fixes the issue. 如果指定函数的返回类型,则可以解决此问题。 And this is often considered good style anyway: 无论如何,这通常被认为是好的风格:

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

Please check if this is what you need 请检查这是否是您需要的

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM