Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin infinite sequences with iterator function

Tags:

kotlin

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

In Java:

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

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) }

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.

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.

If someone would show me how to implement the above Java code in Kotlin it would help a lot.

like image 782
Grayden Hormes Avatar asked Mar 28 '16 02:03

Grayden Hormes


1 Answers

You can use generateSequence factory method:

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

or for the limited case:

generateSequence(0) { it + 2 }.take(100).forEach { println(it) }
like image 63
AndroidEx Avatar answered Nov 04 '22 19:11

AndroidEx