简体   繁体   中英

Why I get type mismatch in “for” expression multigenerator

when I wrote function m like following, I get type mismatch; found : scala.collection.immutable.IndexedSeq[List[(Char, Int)]] required:List[List[(Char, Int)]]

def m(o:List[(Char, Int)]): List[List[(Char, Int)] = o match {
  case Nil => Nil
  case x::xs => for {
    count <- 1 to x._2
    list <- m(xs)      
  } yield (x._1, count)::list
}

But when I switch the two lines in for clause, It's perfectly ok.

  case x::xs => for {
    list <- m(xs)      
    count <- 1 to x._2        
  } yield (x._1, count)::list

The for expression return type is the same as type of first container/monad.

val list = List(1, 2, 3)                         
val array = Array(4, 5, 6)  

for ( l <- list;
      a <- array ) yield l  // produces List(1, 1, 1, 2, 2, 2, 3, 3, 3)

for ( a <- array; 
      l <- list ) yield l   // produces Array(1, 2, 3, 1, 2, 3, 1, 2, 3)

However, the order of '<-' expressions cannot be switched always.

val op = Option(list)

for ( a <- array;
      o <- op ) yield a  // produces Array (4, 5, 6)

for (o <- op;
     a <- array) yield a // does not compile, 
                         // to understand that, we need to de-sugar the for expression
                         // into flatMap and map etc.

I've figured out why. The following expression generates IndexSeq collection which does not match return type List collection

count <- 1 to x._2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM