scala:如果 flatMap 用于在映射函数之后应用 flatten,为什么 flatMap 返回 IndexedS



我正在尝试使用flatMap和map来理解下面的代码段。请解释为什么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 是因为范围,但为什么是 List[(Char,Int(]?

def combinations中,ind是一个List[(Char, Int)]

传递给flatMapind.combinations会产生List[List[(Char, Int)]]flatMap解包第一个列表级别,但不解开结果中返回的第二个列表级别。

为什么flatMap返回IndexedSeq[List[(Char,Int(]]

,而map给出IndexedSeq[(Char,Int(]

这是因为您在flatMap中使用ind.combinations,并且仅在map中使用ind

ind.combinations会给你所有的组合 ind 作为一个List.

您正在将不同的函数传递给平面地图和地图。尝试传递相同的函数,您将看到flatMap is used to apply flatten after a map function

您将看到,如果在comT函数的 map 函数中传递ind.combinations,它将返回IndexedSeq[Iterator[List[(Char,Int)]]]

def comT(occurrencesV: List[(Char, Int)]): IndexedSeq[Iterator[List[(Char,Int)]]] = {
  val ind = for {occ <- occurrencesV
                 x <- (occ._2 to 1 by -1)
  } yield (occ._1,x)
  (1 to 2).map(ind.combinations)
}

Iterator第一个组合函数中展平flatMap

我希望解释清晰易懂

最新更新