我想隱式地將函數A => B
轉換爲List[A] => List[B]
。隱式提升scala
我寫了下面隱含的定義:
implicit def lift[A, B](f: A => B): List[A] => List[B] = ...
不幸的是,當我寫了下面的代碼,含蓄不適用:
val plusOne: (List[Int]) => List[Int] = (x: Int) => (x + 1)
如果我註釋有明確時間的功能,工作正常。
爲什麼?我該如何解決它?
UPDATE。看來這個問題是特定於匿名函數的。比較:
@Test
def localLiftingGenerics {
implicit def anyPairToList[X, Y](x: (X, Y)): List[X] => List[Y] = throw new UnsupportedOperationException
val v: List[String] => List[Int] = ("abc", 239)
}
@Test
def localLiftingFuns {
implicit def fun2ListFun[X, Y](f: X => Y): List[X] => List[Y] = throw new UnsupportedOperationException
val v: List[String] => List[Int] = ((x: String) => x.length)
}
第一個編譯得很好。第二個被標記爲錯誤
您可以提供用於實現「隱式def」的代碼嗎? – 2012-07-11 21:25:23
@ChrisJamesC更新了測試用例 – 2012-07-11 21:28:02
您確定您需要/想要這樣做嗎? 「地圖」爲少數人物購買了很多清晰的內容,例如'val plusOne:(List [Int])=> List [Int] = _ map(_ + 1)'實際上比您的版本短。 – 2012-07-11 21:53:29