为什么此代码有效:
val list = List(('a', 2), ('b', 2))
val first = list.foldRight(List[List[(Char, Int)](List())) {
case ((char, num), acc) =>
(for (
elem <- acc;
i <- 0 to num
) yield (char, i) :: elem)
}
这不是:
val second = list.foldRight(List[List[(Char, Int)]](List())) {
(elem, acc) =>
(for (
elem1 <- acc;
(char, num) <- elem; // ERROR: value filter is not a member of (Char, Int)
i <- 0 to num
) yield (char, i) :: elem1)
}
我是不是两个都做同样的事情,只是在不同的地方?
答案 0 :(得分:3)
使用中流变量绑定代替for生成器来分解for表达式中的元组:
for (
elem1 <- acc;
(char, num) = elem;
i <- 0 to num
) yield ...