【问题标题】:How to create a list with the same element n-times?如何创建具有相同元素 n 次的列表?
【发布时间】:2017-05-27 03:48:59
【问题描述】:

如何创建一个包含 n 次相同元素的列表?

手动实现:

scala> def times(n: Int, s: String) =
 | (for(i <- 1 to n) yield s).toList
times: (n: Int, s: String)List[String]

scala> times(3, "foo")
res4: List[String] = List(foo, foo, foo)

是否还有一种内置方法可以做到这一点?

【问题讨论】:

    标签: scala


    【解决方案1】:

    参见scala.collection.generic.SeqFactory.fill(n:Int)(elem: =>A),扩展集合数据结构,如Seq、Stream、Iterator 等:

    scala> List.fill(3)("foo")
    res1: List[String] = List(foo, foo, foo)
    

    警告它在 Scala 2.7 中不可用。

    【讨论】:

    【解决方案2】:

    像这样使用tabulate,

    List.tabulate(3)(_ => "foo")
    

    【讨论】:

      【解决方案3】:
      (1 to n).map( _ => "foo" )
      

      像魅力一样工作。

      【讨论】:

      • @AlonsodelArte 为什么会浪费?
      • @k0pernikus 因为_ 的值实际上并不重要。你可以做n to 1 by -1、-1 to -n by -1等。
      • @AlonsodelArte 最后,需要一个临时循环变量。即使fill 方法的实现在内部构造了一个临时变量,只要它在列表中产生正确的数量,它的值就无关紧要。所以我不介意未使用的_。
      • @k0pernikus 我不介意在本地 Scala REPL 或 Scastie sn-p 中使用它。但在一个专业项目中,我认为它有足够的理由进行重构。
      【解决方案4】:

      我有另一个模拟我认为的 flatMap 的答案(发现此解决方案在应用 duplicateN 时返回 Unit)

       implicit class ListGeneric[A](l: List[A]) {
        def nDuplicate(x: Int): List[A] = {
          def duplicateN(x: Int, tail: List[A]): List[A] = {
            l match {
             case Nil => Nil
             case n :: xs => concatN(x, n) ::: duplicateN(x, xs)
          }
          def concatN(times: Int, elem: A): List[A] = List.fill(times)(elem)
        }
        duplicateN(x, l)
      }
      

      }

      def times(n: Int, ls: List[String]) = ls.flatMap{ List.fill(n)(_) }
      

      但这是针对预先确定的列表,您希望每个元素复制 n 次

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-19
        • 2019-09-02
        • 1970-01-01
        • 1970-01-01
        • 2020-05-21
        • 2021-09-28
        • 2023-04-07
        • 1970-01-01
        相关资源
        最近更新 更多