2017-09-25 56 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))