Why does the inverse Clojure function return a non-clause sequence?

Why did Clojure reverse function designers decide that the returned sequence is not lazy?
Clojure usually includes lazy strings.

+4
source share
3 answers

Of course, because by definition, in order to undo a sequence, you need to know what is on the other end in order to return what will be the first element in the reverse collection.

Therefore, the sequence must be finite, and you will have to evaluate it in order to use what lies on it.

Application:

The converse does not make sense as an infinite sequence (although it is true to say that infinite sequences are not always a prerequisite for laziness).

If you are going to change the collection, you have already loaded it into memory; it does not need to be counted.

+11
source

rseq returns a sequence that traverses the collection in reverse order. It only works with reversible collections, such as a vector, sorted set, and sorted map.

reverse will change any final seq, but will do so by going through all the elements and transferring them to the list. It is implemented as (reduce conj () coll) . This is clearly not lazy.

+8
source

In addition to Scott's answer :

The reverse function decreases its sequence argument, element by element. If we can make reverse really lazy, we can do the same with other abbreviations. So write a lazy version of reduce :

 (defn lazy-reduce [f init coll] (lazy-seq (if (seq coll) (lazy-reduce f (f init (first coll)) (rest coll)) init))) 

This, by the way, only works with sequences.

But it works:

 (lazy-reduce conj () (range 5)) ; (4 3 2 1 0) 

If we never touch the result, nothing is calculated. We are winning. But as soon as we touch the first element, the whole sequence is realized, unraveling, like knitting with an abandoned stitch.

+1
source

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


All Articles