【问题标题】:scala: if flatMap is used to apply flatten after a map function why flatMap returns IndexedSeq[List[(Char,Int)]] while map give IndexedSeq[(Char,Int)]scala:如果 flatMap 用于在 map 函数之后应用 flatten 为什么 flatMap 返回 IndexedSeq[List[(Char,Int)]] 而 map 给出 IndexedSeq[(Char,Int)]
【发布时间】: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


    【解决方案1】:

    def combinations 中,indList[(Char, Int)]

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

    【讨论】:

      【解决方案2】:

      为什么 flatMap 返回 IndexedSeq[List[(Char,Int)]] 而 map 给出 IndexedSeq[(Char,Int)]

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

      ind.combinations 将为您提供ind所有组合作为List

      您将不同的函数传递给 flatMap 和 map。尝试传递相同的函数,你会看到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展平

      我希望解释清楚易懂

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-10
        • 1970-01-01
        • 2018-05-07
        • 1970-01-01
        • 1970-01-01
        • 2014-02-04
        • 1970-01-01
        相关资源
        最近更新 更多