[英]Type mismatch error in Scala
I am blocked since yesterday about a type mismatch error and I don't see how to correct it. 从昨天开始,我因类型不匹配错误而被阻止,但我看不到如何纠正它。 Maybe you can help me with it.
也许您可以帮助我。
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)) }
Here is the error that I get : 这是我得到的错误:
type mismatch;
found : List[scala.collection.immutable.IndexedSeq[List[(Char, Int)]]]
required: List[forcomp.Anagrams.Occurrences]
The type Occurrences
is defined as type Occurrences = List[(Char, Int)]
类型
Occurrences
定义为type Occurrences = List[(Char, Int)]
How can I fix this error? 如何解决此错误?
You could solve your problem by using flatMap which will concatenate (flatten) the Lists for you. 您可以使用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))) }
Now for each occurance it'll produce a list that has the (x,i)
tuple and the (head._1, occu)
tuple and all of the lists will essentially be ++
'd together by the flatMap. 现在,对于每个事件,它将生成一个包含
(x,i)
元组和(head._1, occu)
元组的列表,所有列表本质上将由flatMap ++
在一起。
Note that I'm blindly converting your code since I know this is homework so I won't attempt to analyze if the algorithm is correct. 请注意,由于我知道这是家庭作业,因此我正在盲目转换您的代码,因此我不会尝试分析算法是否正确。
The problem is that for each member of Occurrences
you yield a List – so you get something like a List[List[Occurrences]]
. 问题在于,对于每个
Occurrences
成员,您都会产生一个List,因此您会得到类似List[List[Occurrences]]
。 I guess you might use flatMap
instead of map
which will flatten the list. 我猜您可能会使用
flatMap
而不是map
来平整列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.