在 Scala 中使用索引进行高效迭代 [英] Efficient iteration with index in Scala

查看:14
本文介绍了在 Scala 中使用索引进行高效迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 Scala 没有带有索引的旧 Java 样式 for 循环,

Since Scala does not have old Java style for loops with index,

// does not work
val xs = Array("first", "second", "third")
for (i=0; i<xs.length; i++) {
  println("String #" + i + " is " + xs(i))
}

我们如何在不使用 var 的情况下高效地进行迭代?

How can we iterate efficiently, and without using var's?

你可以这样做

val xs = Array("first", "second", "third")
val indexed = xs zipWithIndex
for (x <- indexed) println("String #" + x._2 + " is " + x._1)

但是列表被遍历了两次 - 效率不高.

but the list is traversed twice - not very efficient.

推荐答案

比遍历两次更糟糕,它创建了一个中间数组对.您可以使用查看.当您执行 collection.view 时,您可以将后续调用视为在迭代期间懒惰地执行.如果你想取回一个正确的完全实现的集合,你可以在最后调用 force .在这里,这将是无用且昂贵的.所以把你的代码改成

Much worse than traversing twice, it creates an intermediary array of pairs. You can use view. When you do collection.view, you can think of subsequent calls as acting lazily, during the iteration. If you want to get back a proper fully realized collection, you call force at the end. Here that would be useless and costly. So change your code to

for((x,i) <- xs.view.zipWithIndex) println("String #" + i + " is " + x)

这篇关于在 Scala 中使用索引进行高效迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆