2013-05-10 91 views
5

下一個代碼斯卡拉 - 修真類型推斷

def f(chars: List[Char]): List[List[Char]] = chars match { 
    case Nil => List(Nil) 
    case x :: xs => for { 
     v <- f(xs) 
    } yield List(x) :: v 
    } 

提供錯誤消息

- type mismatch; found : List[List[Any]] required: List[List[Char]] 

請幫助我理解爲什麼「的」選擇了這裏最普遍的,而不是任何的字符?我應該閱讀什麼語言規範的主題?謝謝。

回答

10

結果,你是yieldingList[List[List[Char]]]List[List[Char]]的混合。斯卡拉upcasts到List[List[Any]]。對於你的情況下,或者在下面的會做的工作:

scala> def f(chars: List[Char]): List[List[Char]] = chars match { 
    |  case Nil => List(Nil) 
    |  case x :: xs => for { 
    |  v <- f(xs) 
    |  } yield x :: v 
    | } 
f: (chars: List[Char])List[List[Char]] 

scala> def f(chars: List[Char]): List[List[Char]] = chars match { 
    |  case Nil => List(Nil) 
    |  case x :: xs => for { 
    |  v <- f(xs) 
    |  } yield List(x) ++ v 
    | } 
f: (chars: List[Char])List[List[Char]] 
6

的問題是List(x) - 它需要x

首先,v遍歷f(xs)的結果,f返回List[List[Char]]。這意味着結果將是List[X],其中X是由yield返回的類型。

v的類型是List[Char],因爲它遍歷了f(xs)的內容。所以我們必須找出List(x) :: v的類型,這是List[Char]上的List[Char]。它是而不是連接它們:它將列表添加到僅包含字符的列表中。結果列表將包含CharList[Char]

由於同時滿足是Any的唯一類型,然後XAny和的結果爲-理解List[Any]