[英]Type mismatch error in Scala
從昨天開始,我因類型不匹配錯誤而被阻止,但我看不到如何糾正它。 也許您可以幫助我。
def combine( head : (Char,Int), xs : Occurrences) : List[Occurrences] =
xs.map { case (x,i) => for ( occu <- 1 to head._2 ) yield List((x,i), (head._1, occu)) }
這是我得到的錯誤:
type mismatch;
found : List[scala.collection.immutable.IndexedSeq[List[(Char, Int)]]]
required: List[forcomp.Anagrams.Occurrences]
類型Occurrences
定義為type Occurrences = List[(Char, Int)]
如何解決此錯誤?
您可以使用flatMap來解決您的問題,flatMap將為您串聯(平整)列表。
def combine( head : (Char,Int), xs : Occurrences) : List[Occurrences] =
xs.flatMap { case (x,i) => (1 to head._2).map(occu =>List((x,i), (head._1, occu))) }
現在,對於每個事件,它將生成一個包含(x,i)
元組和(head._1, occu)
元組的列表,所有列表本質上將由flatMap ++
在一起。
請注意,由於我知道這是家庭作業,因此我正在盲目轉換您的代碼,因此我不會嘗試分析算法是否正確。
問題在於,對於每個Occurrences
成員,您都會產生一個List,因此您會得到類似List[List[Occurrences]]
。 我猜您可能會使用flatMap
而不是map
來平整列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.