【问题标题】:Packing symbols using scanLeft使用 scanLeft 打包符号
【发布时间】:2019-04-05 05:13:21
【问题描述】:

99 scala problems有这个问题:

将列表元素的连续重复项打包到子列表中。 如果列表包含重复的元素,则应将它们放在单独的子列表中。

Example:
scala> pack(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
res0: List[List[Symbol]] = List(List('a, 'a, 'a, 'a), List('b), List('c, 'c), List('a, 'a), List('d), List('e, 'e, 'e, 'e))

我了解解决上述问题的尾递归方式。我想知道是否有一种方法可以使用 scanLeft 完成上述操作,其中中间结果是常见元素的列表?

【问题讨论】:

    标签: list scala traversal tail-recursion


    【解决方案1】:

    这是使用foldLeft的解决方案:

    def pack[A](l:List[A]): List[List[A]] = l match {
      case head :: tail =>
        tail.foldLeft(List(List(head))) { (collector:List[List[A]], elem:A) =>
          if (collector.head.head == elem)
            (elem +: collector.head) +: collector.tail
          else
            List(elem) +: collector
        }.reverse
      case _ => List.empty
    }
    

    这仅适用于列表。 更好的解决方案可能会使用MultiSets,尽管很难找到 Scala 实现。

    【讨论】:

      【解决方案2】:

      简洁但未优化的版本可能如下所示:

      val l = List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)
      for (i <-l.distinct) yield l.filter(_ == i)
      
      res0: List[List[Symbol]] = List(List('a, 'a, 'a, 'a, 'a, 'a), List('b), List('c, 'c), List('d), List('e, 'e, 'e, 'e))
      

      【讨论】:

      • 您的结果不是预期的。结果应该是 List(List('a, 'a, 'a, 'a), List('b), List('c, 'c), List('a, 'a), List('d) , 列表('e, 'e, 'e, 'e))
      【解决方案3】:

      从Scala 2.13 开始,List 现在提供了unfold 构建器,可以与List::span 结合使用:

      // val list = List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)
      List.unfold(list) {
        case Nil  => None
        case rest => Some(rest.span(_ == rest.head))
      }
      // List[List[Symbol]] = List(List('a, 'a, 'a, 'a), List('b), List('c, 'c), List('a, 'a), List('d), List('e, 'e, 'e, 'e))
      

      或者,加上Scala 2.13的Option#unless builder:

      List.unfold(list) {
        rest => Option.unless(rest.isEmpty)(rest.span(_ == rest.head))
      }
      

      详情:

      • Unfold 使用一个内部状态,在我们的例子中使用 list 初始化来拆分 List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)
      • 在每次迭代中,我们span 那个内部状态,以便找到包含相同符号的前缀:l.span(_ == l.head),这是在第一次迭代中l.span(_ == 'a) 并给出(List('a, 'a, 'a, 'a),List('b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
      • 正如unfold 期望每次迭代都有一个元组的Option,其第一部分是要添加到正在构建的列表中的新元素(此处为List('a, 'a, 'a, 'a)),其第二部分是内部状态的新值(此处为 List('b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)),该跨度完全符合该要求。
      • 我们不断迭代相同的步骤,直到内部列表为空,在这种情况下,我们通过返回 None 来告诉 unfolding 我们已完成。

      【讨论】:

        【解决方案4】:

        不,scanLeft 在这种情况下不是合适的方法。 scanLeft 将产生一组结果,列表中的每个值都有一个元素,加上您提供的初始值。因此,例如在 List(1,2,3,4) 上使用 scanLeft 将始终产生包含 5 个元素的结果

        例如

        scala> List(1,2,3,4).scanLeft(">"){case (last, x) => last + x}
        res7: List[String] = List(>, >1, >12, >123, >1234)
        

        【讨论】:

          【解决方案5】:

          scanLeft 对于计算前缀总和很有用,但问题中并非如此。您可以尝试将其与其他调用结合使用,但我认为这不是解决问题的好方法。

          foldLeft 似乎对这项任务更有用。

          def pack[T](list: Seq[T]) = list.foldLeft(new ArrayBuffer[ArrayBuffer[T]])((ret, el) => {
              if (ret.isEmpty || ret.last.head != el)
                ret.append(new ArrayBuffer[T])
              ret.last.append(el)
              ret
            })
          

          留给好奇的读者两个简单的任务:

          • 使用 List prepending 使其纯粹是功能性的
          • 制作正确的返回类型

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-04-07
            • 2011-11-23
            • 1970-01-01
            • 2017-11-14
            • 1970-01-01
            • 2019-10-28
            • 2021-04-17
            • 1970-01-01
            相关资源
            最近更新 更多