Clojure Lazy Sequences: Equivalents in Kotlin - clojure

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 a seed.
fun <T : Any> generateSequence(
seed: T?,
nextFunction: (T) -> T?
): Sequence<T> (source)
Returns a sequence defined by the starting value seed and the function nextFunction, which is invoked to calculate the next value based on the previous one on each iteration.
The following will show some examples comparing Clojure with Kotlin sequences.
1. A simple take from an infinite sequence of one static value
Clojure
(take 3 (repeat "Hello StackOverflow"))
Kotlin
generateSequence { "Hello StackOverflow" }.take(3).toList()
These are pretty similar. In Clojure we can use repeat and in Kotlin it's simply generateSequence with a static value that will be yielded for ever. In both cases, take is 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 take from an infinite sequence of an dynamic value
Clojure
(take 5 (iterate inc 1))
Kotlin
generateSequence(1) { it.inc() }.take(5).toList()
This example is a bit different because the sequences yield the increment of the previous value infinitely. The Kotlin generateSequence can be invoked with a seed (here: 1) and a nextFunction (incrementing the previous value).
3. A cyclic repetition of values from a list
Clojure
(take 5 (drop 2 (cycle [:first :second :third ])))
// (:third :first :second :third :first)
Kotlin
listOf("first", "second", "third").let { elements ->
generateSequence(0) {
(it + 1) % elements.size
}.map(elements::get)
}.drop(2).take(5).toList()
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:
fun <T> List<T>.cyclicSequence() = generateSequence(0) {
(it + 1) % this.size
}.map(::get)
listOf("first", "second", "third").cyclicSequence().drop(2).take(5).toList()
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
(defn factorial [n]
(apply * (take n (iterate inc 1))))
We take n values from a sequence that yields an incrementing number starting with 1 and accumulate them with the help of apply.
Kotlin
fun factorial(n: Int) = generateSequence(1) { it.inc() }.take(n).fold(1) { v1, v2 ->
v1 * v2
}
Kotlin offers fold which let's us accumulate the values easily.

Related

Clojure loop through a vector starting from the nth element not 0

I would like to loop through a vector starting from the nth element not 0;
How it looks like in Java:
for(int i = firstIndex; i <= lastIndex; i++) {
newText += contents[i] + " ";
}
If you are always dealing with a vector, then subvec is a good choice. For example:
(subvec contents firstIndex)
If you want to be compatible with sequences in general, you'll want to use drop. drop is O(n) w.r.t. the number of elements dropped, which subvec is always O(1). If you're only ever dropping a few elements, the difference is negligible. But for dropping a large number of elements (i.e., large firstIndex), subvec will be a clear winner. But subvec is only available on vectors.
You can use the drop function to skip first n elements and then loop over the result. For example, if you want to skip two first elements:
user=> (drop 2 [1 2 3 4])
(3 4)
The following can possibly do the same that the Java form you provided:
(require '[clojure.string :as str])
(str/join " " (drop first-index contents))

How can I define x as a list of integers to evaluate a polynomial for all elements in x?

The polynomial:
(modulo (+ (expt x 2) 2) 5)
I want to do something like
(define x <list of integers like 0, ..., 10>)
It should then output the result(s) like:
3
1
1
3
...
Do I have to write a separate method to get this working or does Scheme have something built-in?
The way you have it written won't work. In you're polynoimial your taking expt of x directly, which if you define it to be a list, will result in a run-time error.
(map (lambda (x) (modulo (+ (expt x 2) 2) 5)) (iota 11 1 1))
;Value 2: (3 1 1 3 2 3 1 1 3 2 3)
What I did was wrap up your polynomial as an anonymous function, and used it as an argument to map. The second argument (iota count start step) generates a list of length count starting at start and proceeding by and addition of step. start and step are optional argument defaulting to 0 and 1 respectively.
Map is a higher order function which accepts a function as it's first argument and one or more lists afterwards. To simplify thing's I'll ignore cases where more than one list is use. The new list meets the condition that any given element is the result of applying the function to the corresponting element of the original list.
(map f (x y z ...)) -> ((f x) (f y) (f z) ...)
I am not sure what you are asking, but if you want to construct a list of incrementing integers, to each element of which you can apply your polynomial function, SRFI-1 has the iota procedure. So
(iota 10)
will construct a list of 10 integers in the range 0 to 9. iota optionally takes additional start and step arguments. To apply the polynomial function to each integer and construct a new list of the results, you can use map.

Append integer to global list inside function haskell

I'll use a simple example for what I'm trying to do.
Say I have the list:
nums = []
Now I have the function:
allNums n = nums.append(n)
So if I run the function:
allNums 6
The list nums should have the values
[6]
I know nums.append doesn't work, but what code could replace that.
Simple Answer:
You can't do that. Haskell is a pure, functional language, that means:
A function does not have any side effect.
A function does always return the same result when called with the same parameters.
A function may or may not be called, but you don't have to care about that. If it wasn't called, it wasn't needed, but because the function does not have any side effects, you won't find out.
Complex answer:
You could use the State Monad to implement something that behaves a bit like this, but this is probably out of reach for you yet.
I'm suggesting to use an infinite list instead of appending to global variable.
It's true haskell is pure functional. But also it's lazy. Every part of data is not calculated until is really needed. It also applies to collections. So you could even define a collection with elements based on previous elements of same collection.
Consider following code:
isPrime n = all (\p -> (n `mod` p) /= 0 ) $ takeWhile (\p ->p * p <= n) primes
primes = 2 : ( filter isPrime $ iterate (+1) 3 )
main = putStrLn $ show $ take 100 primes
definition of isPrime is trivia when primes list is defined. It takes pack of primes which is less or equivalent to square root of examining number
takeWhile (\p ->p * p <= n) primes
then it checks if number have only non-zero remainders in division by all of these numbers
all (\p -> (n `mod` p) /= 0 )
the $ here is an application operator
Next using this definition we taking all numbers starting from 3:
iterate (+1) 3
And filtering primes from them.
filter isPrime
Then we just prepending the first prime to it:
primes = 2 : ( ... )
So primes becomes an infinite self-referred list.
You may ask: why we prepending 2 and just no starting filtering numbers from it like:
primes = filter isPrime $ iterate (+1) 2
You could check this leads to uncomputable expression because the isPrime function needs at least one known member of primes to apply the takeWhile to it.
As you can see primes is well defined and immutable while it could have as many elements as you'll need in your logic.

Clojure - map function

As we know, (map f [a b c]) is equivalent to [(f a) (f b) (f c)].
My question is: The evaluation result of (map #(- (int %) (int \0)) "1234") is (1 2 3 4), why does it return the results of applying #(- (int %) (int \0)) to every digits of "1234", rather than the string "1234" as a whole? How should I understand this code example?
map calls seq on all arguments after the first. seq turns a string into a sequence of characters.
Clojure can treat a string as a sequence - of characters. This is useful because you can:
map things over the string
partition the string
get locations by index
do everything else sequences do.
It's perhaps a bit annoying having to remember to put the resulting sequence back into a string by wrapping the sequence manipulating expression in a call to str.

reduce-while function in clojure?

I am new to Clojure programming, and would like to know what is the idiomatic way to do the following thing:
I would like to sum a collection of numbers nums, which may contains a large number of numbers, let's assume there are only positive numbers.
I don't care the exact sum if the sum is very large. For example, if the sum of the numbers is larger than 9999, I would simply return 10000 without summing the remaining numbers at all.
If I implement it with some OO language such as Java, I may do it like below:
private int sum(int[] nums) {
int sum = 0;
for(int n : nums) {
if(sum > 9999) {
sum = 10000;
break;
} else {
sum += n;
}
}
return sum;
}
A naive implementation in Clojure may look like:
(let [sum (reduce + nums)]
(if (> sum 9999) 10000 sum))
However, this seems to waste some CPU resource to sum the entire collection of numbers, which is not desired. I am looking for something like take-while function but for reduce, but cannot find it. Is there something like:
(reduce-while pred f val coll)
Or is there any other Clojure idiomatic way to solve this problem? I think the solution can be applied to a set of problems requiring similar logic.
Any comment is appreciated. Thanks.
If you're using Clojure 1.5.x then you may take advantage of new reduced function:
(reduce #(if (> %1 9999) (reduced 10000) (+ %1 %2)) nums)
One of the lesser known Clojure functions seems to be reductions. It will give you all the intermediate results of your computation:
(reductions + (range 4)) ;; => (0 1 3 6)
(reduce + (range 4)) ;; => 6
The last element of reductions' result seq will be the reduced value. There are multiple ways to enforce your predicate, e.g. using some:
(let [sums (reductions + nums)]
(if (some #(> % 9999) sums)
10000
(last sums)))
The reduce/reduced version given by #leonid-beschastny is probably faster (no lazy sequence overhead, reducers, ...) but this one will work in earlier Clojure versions, too.