在 Scala 2.8 集合中,为什么在 Iterable 之上添加了 Traversable 类型? [英] In Scala 2.8 collections, why was the Traversable type added above Iterable?

查看:28
本文介绍了在 Scala 2.8 集合中,为什么在 Iterable 之上添加了 Traversable 类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道要Traversable,你只需要一个foreach 方法.Iterable 需要一个 iterator 方法.

I know that to be Traversable, you need only have a foreach method. Iterable requires an iterator method.

Scala 2.8 集合 SID 和Fighting Bitrot with Types"论文基本上都没有提到为什么添加 Traversable 的主题.SID 只说David McIver……提出了 Traversable 作为 Iterable 的概括."

Both the Scala 2.8 collections SID and the "Fighting Bitrot with Types" paper are basically silent on the subject of why Traversable was added. The SID only says "David McIver... proposed Traversable as a generalization of Iterable."

我从关于 IRC 的讨论中模糊地了解到,它与在遍历集合终止时回收资源有关吗?

I have vaguely gathered from discussions on IRC that it has to do with reclaiming resources when traversal of a collection terminates?

以下可能与我的问题有关.TraversableLike.scala 中有一些看起来很奇怪的函数定义,例如:

The following is probably related to my question. There are some odd-looking function definitions in TraversableLike.scala, for example:

def isEmpty: Boolean = {
  var result = true
  breakable {
    for (x <- this) {
      result = false
      break
    }
  }
  result
}

我认为有一个很好的理由不只是写成:

I assume there's a good reason that wasn't just written as:

def isEmpty: Boolean = {
  for (x <- this)
    return false
  true
}

推荐答案

我在 IRC 上向 David McIver 询问了这个问题.他说他不再记得所有的原因,但它们包括:

I asked David McIver about this on IRC. He said he no longer remembered all of the reasons, but they included:

  • 迭代器通常很烦人……要实现"

  • "iterators are often annoying... to implement"

迭代器有时不安全(由于在循环开始和结束时设置/拆卸)"

iterators are "sometimes unsafe (due to setup/teardown at the beginning and end of the loop)"

希望通过 foreach 而不是通过迭代器来实现某些东西能提高效率(目前的 HotSpot 编译器不一定能实际展示这种效果)

Hoped-for efficiency gains from implementing some things via foreach rather than via iterators (gains not necessarily yet actually demonstrated with the current HotSpot compiler)

这篇关于在 Scala 2.8 集合中,为什么在 Iterable 之上添加了 Traversable 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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