Clojure provides means for lazy evaluation of values in (infinite) sequences. With this, values will only be computed when they get actually consumed.
An example of an infinite sequence of one repeated element:
(take 3 (repeat "Hello StackOverflow"))
//=> ("Hello StackOverflow" "Hello StackOverflow" "Hello StackOverflow")
Using take helps to only consume as many elements from the sequence as we want. Without it, an OutOfMemoryError would kill the process quickly.
Another example of an infinite sequence is the following:
(take 5 (iterate inc 1))
//(1 2 3 4 5)
Or a more advanced sequence providing the factorial function:
((defn factorial [n]
(apply * (take n (iterate inc 1)))) 5)
Does Kotlin provide similar sequences? How do they look like?
I answered the question myself in order to document the knowledge here. This is fine according to Can I answer my own question?
In Kotlin, we can also make use of lazy evaluation using Sequences, too. In order to create a sequence, we may use
generateSequence(with or without providing aseed.The following will show some examples comparing Clojure with Kotlin sequences.
1. A simple
takefrom an infinite sequence of one static valueClojure
Kotlin
These are pretty similar. In Clojure we can use
repeatand in Kotlin it's simplygenerateSequencewith a static value that will be yielded for ever. In both cases,takeis being used in order to define the number of elements we want to compute.Note: In Kotlin, we transform the resulting sequence into a list with
toList()2. A simple
takefrom an infinite sequence of an dynamic valueClojure
Kotlin
This example is a bit different because the sequences yield the increment of the previous value infinitely. The Kotlin
generateSequencecan be invoked with a seed (here:1) and anextFunction(incrementing the previous value).3. A cyclic repetition of values from a list
Clojure
Kotlin
In this example, we repeat the values of a list cyclically, drop the first two elements and then take 5. It happens to be quite verbose in Kotlin because repeating elements from the list isn't straightforward. In order to fix it, a simple extension function makes the relevant code more readable:
4. Factorial
Last but not least, let's see how the factorial problem can be solved with a Kotlin sequence. First, let's review the Clojure version:
Clojure
We take n values from a sequence that yields an incrementing number starting with 1 and accumulate them with the help of
apply.Kotlin
Kotlin offers
foldwhich let's us accumulate the values easily.