2017-09-25 30 views
0

我试图使该组合本身功能的扩展功能 -缺少的参数类型以下划线

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作为参数传递给辅助函数,但有错误:

Error:(26, 11) missing parameter type for expanded function ((x$1: ) => helper(x$1, n)) helper(_,n)

^

回答

2

根据我的经验, _句法糖有点挑剔,斯卡拉的类型推断并不完美,它的工作原理很简单但在一些更微妙的情况下,有时您必须自己提供类型信息。也许别人可以解释为什么这里是这种情况。

如果指定函数的返回类型,它将修复问题。而这通常被认为是良好的作风反正:

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

请检查,如果这是你所需要的

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