Search code examples
scalatype-mismatch

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)]

How can I fix this error?


Solution

  • You could solve your problem by using flatMap which will concatenate (flatten) the Lists for you.

    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.

    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.