在 scala 2.7.5 中对迭代器进行分区

发布于 2024-08-06 15:43:55 字数 339 浏览 4 评论 0原文

看起来 scala 2.7.5 中的 Iterator 上没有 partition 方法(2.8 中有)。我希望在不失去迭代器懒惰的情况下进行分区,因此以下不是选项:

itr.toList.partition( someTest(_) )

任何人都可以推荐一种方法吗在不实现我自己的 partition 方法的情况下执行此操作?例如,是否有某种方法可以将 Iterator 转换为延迟评估的 Stream

It looks as though there is no partition method on an Iterator in scala 2.7.5 (there is in 2.8). I'd like to have a partition without losing the laziness of the Iterator, so the following is not an option:

itr.toList.partition( someTest(_) )

Can anyone recommend a way of doing this without implementing my own partition method? For example, is there some way of converting an Iterator into a lazily-evaluated Stream?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╄→承喏 2024-08-13 15:43:55

您是否尝试过 Stream.fromIterator 方法?它生成一个包含给定迭代器的元素的流:)。

一个例子是:

val iter = List(1,2,3,4).elements // just a simple iterator

val str = Stream.fromIterator(iter)

str.partition(_ >= 3)

希望它有帮助(这就是你想要的)。

编辑:只是一个例子来表明这是懒惰的(并且是记忆的 - 就像所有Stream一样)。

scala> val iter = new Iterator[Int] {
     | var lst = List(1,2,3,4)
     | def hasNext() = !lst.isEmpty
     | def next() = { val x = lst.head; println(x); lst = lst.tail; x }
     | }

scala> val stream = Stream.fromIterator(iter)
1
stream: Stream[Int] = Stream(1, ?)

scala> stream.partition(_ >= 2)
2
3
4
res1: (Iterable[Int], Iterable[Int]) = (ArrayBuffer(2, 3, 4),ArrayBuffer(1))

scala> stream.partition(_ >= 3)
res2: (Iterable[Int], Iterable[Int]) = (ArrayBuffer(3, 4),ArrayBuffer(1, 2))

注意:遗漏了一些输出,因为它非常冗长。

——弗拉维·西普西甘

Have you tried the Stream.fromIterator method? It produces a stream containing the elements of the given iterator :).

An example would be:

val iter = List(1,2,3,4).elements // just a simple iterator

val str = Stream.fromIterator(iter)

str.partition(_ >= 3)

Hope it helps (and it is the thing you had in mind).

EDIT: Just an example to show that this is lazy (and memoised - as all Streams are).

scala> val iter = new Iterator[Int] {
     | var lst = List(1,2,3,4)
     | def hasNext() = !lst.isEmpty
     | def next() = { val x = lst.head; println(x); lst = lst.tail; x }
     | }

scala> val stream = Stream.fromIterator(iter)
1
stream: Stream[Int] = Stream(1, ?)

scala> stream.partition(_ >= 2)
2
3
4
res1: (Iterable[Int], Iterable[Int]) = (ArrayBuffer(2, 3, 4),ArrayBuffer(1))

scala> stream.partition(_ >= 3)
res2: (Iterable[Int], Iterable[Int]) = (ArrayBuffer(3, 4),ArrayBuffer(1, 2))

NB: left some output out as it was quite verbose.

-- Flaviu Cipcigan

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文