简体   繁体   中英

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:

Error:(26, 11) missing parameter type for expanded function ((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. 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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