There is no random access for lazy sequences in Clojure.
In a sense, you can consider them equivalent to singly linked lists β you always have the current element and function to get the next.
That way, even if you just call (last some-seq)
, it will evaluate all the elements of the sequence, even if the sequence is lazy. If the sequence is finite and small enough (and if you do not hold the head of the sequence in the link) it is good when it comes to memory. As you noted, there is a problem with the runtime that can occur if the function used to get the next element is expensive.
In this case, you can compromise to use a cheap function to go all the way to the last element:
(last some-seq)
and then apply the function only to this result:
(expensive (last some-seq))
source share