当我写下函数m时,我得到了 类型不匹配; 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
}
但是当我在for子句中切换两行时,完全可以。
case x::xs => for {
list <- m(xs)
count <- 1 to x._2
} yield (x._1, count)::list
答案 0 :(得分:7)
for
表达式返回类型与第一个容器/ 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)
但是,'&lt; - '表达式的顺序不能始终切换。
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.
答案 1 :(得分:-1)
我弄明白了为什么。以下表达式生成不匹配的IndexSeq集合 返回类型列表集合
count <- 1 to x._2