具有迭代器功能的Kotlin无限序列 [英] Kotlin infinite sequences with iterator function
问题描述
我对如何在Kotlin中创建一个无限序列用于惰性评估感到困惑.
I am confused about how to create an infinite sequence in Kotlin to use for lazy evaluation.
在Java中:
IntStream.iterate(0, i -> i + 2)
.limit(100)
.forEach(System.out::println);
,但是序列似乎比Java流更加混乱.序列构造函数非常令人困惑,因为它说:
but sequences seem much more confusing then Java streams. The sequence constructor is very confusing the doc for it says:
/**
* Given an [iterator] function constructs a [Sequence] that returns values through the [Iterator]
* provided by that function.
* The values are evaluated lazily, and the sequence is potentially infinite.
*/
但我不知道迭代器函数的含义或如何制作迭代器函数.
but I don't know what it means by an iterator function or how to make one.
Sequence { iterator(arrayOf<Int>()) }
.forEach { print(it) }
我有可以编译的文件,但是显然不打印任何东西.我认为我的迭代器函数没有任何意义.它需要一个不带任何参数并返回迭代器的函数,这根本不像Java .iterate
函数.迭代器碰巧有一个采用数组的构造函数,如果我有要在数组中使用的数据集,那是有意义的,但我没有.我想使用无限序列.
I have this which compiles but obviously doesn't print anything. I don't think my iterator function makes any sense. It wants a function that takes no arguments and returns an iterator, which isn't like the Java .iterate
function at all. Iterator happens to have a constructor that takes an array, which would make sense if I had a data set to work with in an array but I don't. I want to be working with an infinite sequence.
没有.limit
,因此我以前尝试添加.reduce
,但是.reduce
的参数更加混乱.我认为应该有一个.toList
,但是我知道它没有用,所以我没有尝试过.
There is no .limit
, so I previously tried to add a .reduce
but the arguments for .reduce
were even more confusing. I think there should be a .toList
but I knew it wasn't working so I didn't try it.
如果有人向我展示如何在Kotlin中实现上述Java代码,将会大有帮助.
If someone would show me how to implement the above Java code in Kotlin it would help a lot.
推荐答案
You can use generateSequence
factory method:
generateSequence(0) { it + 2 }.forEach { println(it) }
或在特定情况下:
generateSequence(0) { it + 2 }.take(100).forEach { println(it) }
这篇关于具有迭代器功能的Kotlin无限序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!