2017-07-28 47 views
1

我寫了類似map1功能List.map爲:什麼是錯的使用拉姆達這裏

def map1[A, B](xs: List[A], f: A => B): List[B] = { 
    xs match { 
    case List() => scala.collection.immutable.Nil 
    case head :: tail => f(head) :: map1(tail, f) 
    } 
} 

現在,當我撥打上面:

map1(List(1, 2, 3), x => x + 1) 

我得到的錯誤爲:error: missing parameter type。但下列作品:

List(1, 2, 3).map(x => x + 1) 

爲什麼map1不適用於lamdas?

+1

這不是一個拉姆達問題,因爲這個作品'(X:強度)=> X + 1'。這是類型推理引擎的一個問題。 – jwvh

+0

推論問題:類型'A'可以從'xs'推斷爲'f',就像在相同的參數列表中一樣 – cchantep

回答

4

在Scala中,參數類型推理在參數列表之間起作用,而不是在參數列表中。爲了幫助編譯器推斷出類型,移動f到它自己的參數列表:

def map1[A, B](xs: List[A])(f: A => B): List[B] = { 
    xs match { 
    case Nil => scala.collection.immutable.Nil 
    case head :: tail => f(head) :: map1(tail)(f) 
    } 
}