【发布时间】:2018-03-25 16:59:23
【问题描述】:
我正在尝试使用 flatMap 和地图来理解以下代码。请解释为什么 flatMap 返回 IndexedSeq[List[(Char,Int)]]:
使用flatMap:
def combinations(
occurrencesV: List[(Char, Int)]): IndexedSeq[List[(Char, Int)]] = {
val ind = for {
occ <- occurrencesV
x <- (occ._2 to 1 by -1)
} yield (occ._1, x)
(1 to 2).flatMap(ind.combinations)
}
combinations(List(('a', 2), ('e', 1), ('t', 2)))
使用map:
def comT(occurrencesV: List[(Char, Int)]): IndexedSeq[(Char, Int)] = {
val ind = for {
occ <- occurrencesV
x <- (occ._2 to 1 by -1)
} yield (occ._1, x)
(1 to 2).map(ind)
}
comT(List(('a', 2), ('e', 1), ('t', 2)))
我知道 IndexedSeq 是因为 Range,但为什么是 List[(Char,Int)]?
【问题讨论】:
标签: scala