【问题标题】:zipWithIndex for nested collections (release without mutable state)用于嵌套集合的 zipWithIndex(发布时没有可变状态)
【发布时间】:2014-09-15 11:52:14
【问题描述】:

有一些嵌套的集合:

val xs = List(
           List("a","b"), 
           List("c"), 
           List("d", "e", "f"))

我想为嵌套列表的元素创建唯一索引:

val result = List(
         List(("a", 0), ("b", 1)), 
         List(("c", 2)),
         List(("d", 3), ("e", 4), ("f", 5)))

这是一个糟糕的解决方案(使用可变状态):

val indexes:List[Int] = xs.flatten.zipWithIndex.map(_._2)
var idx = 0
val result = xs.map(_.map{ el =>
   val copy = (el, indexes(idx))
   idx = idx + 1
   copy
})

如何释放这个不可变状态的任务?

【问题讨论】:

  • 请注意,使用可变状态并不是一个糟糕的解决方案,在某些情况下您确实想使用可变状态,因为它们使您的代码更清晰,在这种情况下我肯定会使用可变状态,直观、简单,您不会创建太多变量或中间集合。无论如何,出于好奇,我还希望看到一个纯粹的功能解决方案。
  • 确实,如果我们查看 zipWithIndex github.com/scala/scala/blob/v2.11.2/src/library/scala/… 的来源,我们会看到.. 一个可变的当前索引!

标签: scala


【解决方案1】:

解决方案1(使用fold):

scala> xs.foldLeft((List[List[(String, Int)]](), 0)){ 
         case ((r, i), x) => (r:+x.zip(Stream.from(i)), i+x.size) 
       }._1
res1: List[List[(String, Int)]] = List(List((a,0), (b,1)), List((c,2)), List((d,3), (e,4), (f,5)))

解决方案2(使用递归)

scala> def deepZip[A](ls: List[List[A]], i: Int = 0): List[List[(A, Int)]] = ls match {
     |   case Nil => Nil
     |   case x::xs => x.zip(Stream.from(i)) :: deepZip(xs, i+x.size)
     | }
deepZip: [A](ls: List[List[A]], i: Int)List[List[(A, Int)]]

scala> deepZip(xs)
res2: List[List[(String, Int)]] = List(List((a,0), (b,1)), List((c,2)), List((d,3), (e,4), (f,5)))

解决方案 3:

scala> (xs, xs.map(_.size).scanLeft(0){ _+_ }).zipped map { (a, b) => a.zip(Stream.from(b)) }
res3: List[List[(String, Int)]] = List(List((a,0), (b,1)), List((c,2)), List((d,3), (e,4), (f,5)))

【讨论】:

  • #1 是我的第一个想法。 #3 是很好的预计算 b,而且对眼睛很容易。效率较低的变体,但对眼睛和大脑很容易:xs.zipWithIndex map { case (xx, i) => xx zip (Stream from xs.take(i).map(_.size).sum) }
【解决方案2】:

另一种变化:

val index = Iterator.from(0)
for (sl <- xs) yield for (e <- sl) yield (e, index.next)

IMO 相当简洁,但迭代器当然不是纯函数式的

而且是功能性的,可读性很强(对我来说,无论如何)

 val starts = xs.scanLeft(0)(_ + _.size)
 (xs, starts, starts.tail).zipped map{ (sl, start, end) => sl zip ( start until end)}

【讨论】:

  • 这很好。您可以通过在第一个循环中嵌入第二个 for 循环来缩短它:for (sl &lt;- xs; e &lt;- sl) yield (e, index.next)
  • @IonutGStan,不,你不能。这最终使列表变平。
【解决方案3】:

您始终可以应用足够的蛮力将命令式 while 循环转换为函数式 foldLeft:

val xs = List(List("a", "b"), List("c"), List("d", "e", "f"))

def addIndeces(xs: List[List[String]]): List[List[(String, Int)]] = {
  val outerLoopState = 0 -> Vector.empty[List[(String, Int)]]

  val (finalCounter, finalResult) = xs.foldLeft(outerLoopState) {
    case ((counter, result), sublist) =>
      val innerLoopState = counter -> Vector.empty[(String, Int)]
      val (newCounter, subResult) = sublist.foldLeft(innerLoopState) {
        case ((counter, subResult), element) =>
          (counter + 1, subResult :+ (element, counter))
      }

      (newCounter, result :+ subResult.toList)
  }

  finalResult.toList
}

// scala> addIndeces(xs)
// res0: List[List[(String, Int)]] = List(List((a,0), (b,1)), List((c,2)), List((d,3), (e,4), (f,5)))

我已将Vector 用于中间结果,以获得更有效的功能append 操作。使用List,我将不得不预先添加然后反转中间结果。

【讨论】:

  • 与@Eastsun 相比,这是很多 LOC(ALOLOC?)。
【解决方案4】:

这是我想出的:

def iterate(someList: List[List[Int]], counter: Int = 0, acc: List[List[(Int, Int)]] = List()): List[List[(Int, Int)]] = someList match {
  case head :: tail =>
    val newCounter = counter + head.length
    val sublist = head.zipWithIndex.map {
      // add the counter to the index
      case (v, i) => (v, i + counter)
    }
    // recurse
    iterate(tail, newCounter, acc :+ sublist)
  case _ => acc
}

scala> iterate(List(List(1,2), List(3,4)))
res3: List[List[(Int, Int)]] = List(List((1,0), (2,1)), List((3,2), (4,3)))

scala> iterate(List(List(1,2), List(3,4), List(5)))
res4: List[List[(Int, Int)]] = List(List((1,0), (2,1)), List((3,2), (4,3)), List((5,4)))

这基本上是迭代一个列表列表,使用索引压缩每个子列表并添加一个计数器值,该计数器值考虑了所有先前列表的长度,当列表为空时,我们返回一个累加器。

但正如我所说,我不会用可变版本来交换它。

【讨论】:

  • acc.:+(foo) 语法不是仅用于晦涩的编译器调试输出吗? acc :+ sublist
  • 作为单行:def zipdeep[A](xx: List[List[A]], count: Int = 0, res: List[List[(A, Int)]] = Nil): List[List[(A, Int)]] = xx match { case a :: b =&gt; zipdeep(b, count+a.size, res :+ (a.zipWithIndex map { case (v,i) =&gt; (v,i+count) })) case _ =&gt; res }
  • 奇怪的是,我有时会使用这一点(比如.:+),有时不使用(比如++),至于一个班轮,我在第一个答案中有类似的东西,我然后移动变量中的所有代码以使其更具可读性。
  • 是的,这很奇怪。我只尝试了单线,看看它是否显示了递归的整洁程度。奥德斯基在某处说折叠通常比递归函数更简单。
【解决方案5】:

普通的非尾递归...

 def zipFrom[A](start:Int)(l:List[A]):(List[(A,Int)],Int) = {
  val end = start + l.length
  val ys = l zip (start to end)
  ys -> end
 }

 def zp[A](xs:List[List[A]],acc:Int):List[List[(A,Int)]] = xs match {
  case Nil    => Nil
  case h :: t =>
   val (l,e) = zipFrom(acc)(h)
   l :: zp(t,e)
  }

【讨论】:

    【解决方案6】:
    var index = 0
    val lim = li.map {
      case l @ List(_*) =>
        val s = index
        index += l.length
        l.zip(s until index)
    }
    

    它工作起来又快又简单

    【讨论】:

    • 那里有一些冗余位。 case l @List(_*)=&gt; 可以是l =&gt;,范围内不需要.toList。
    【解决方案7】:

    @Archetypal Paul 使用 map 而不是 for 的变体

    val ys = Iterator.from(0)
    val zs = xs.map { _.map ((_,ys.next)) }
    

    使用 zip & iterator & map 的变化

    val ys = xs.flatten.zipWithIndex.iterator
    val zs = xs.map { _.map ( x=> ys.next) }
    

    【讨论】:

      猜你喜欢
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 2015-08-25
      • 2018-03-14
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      相关资源
      最近更新 更多