Kotlin infinite sequences with iterator function

I am confused about how to create an infinite sequence in kotlin for lazy evaluation.

In java:

IntStream.iterate(0, i -> i + 2) .limit(100) .forEach(System.out::println); 

but sequences seem a lot more confusing than java threads. The sequence constructor is very confusing the document as 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 using the iterator function or how to do it.

 Sequence { iterator(arrayOf<Int>()) } .forEach { print(it) } 

I have this one that compiles but obviously doesn't print anything. I don't think my iterator function makes sense. He wants a function that takes no arguments and returns an iterator that is not at all like the java.iterate function. The iterator has a constructor that takes an array, which would make sense if I had a dataset to work in the array, but I do not. I want to work with infinite sequence.

No .limit, so I previously tried to add .reduce, but the arguments for .reduce were even more confusing. I think there should be a .toList, but I knew that it did not work, so I did not try.

If someone shows me how to implement the above Java code in lotlin, it will help a lot.

+5
source share
1 answer

You can use the generateSequence factory method:

 generateSequence(0) { it + 2 }.forEach { println(it) } 

or for a limited case:

 generateSequence(0) { it + 2 }.take(100).forEach { println(it) } 
+16
source

Source: https://habr.com/ru/post/1245886/


All Articles