Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

next and rest in clojure

I am reading explanations on rest vs next in clojure. As I understand it, it breaks down to next evaluating/realizing the tail of the sequence, to know wether it should return nil or not, while rest always returns sequence, so it is lazier.

However, what I dont understand is this: both functions need to know wether there is something in the tail. One will return nil if there is nothing left, other one will return ().

So basicaly, they both need to check/evaluate what is left. Cause even rest, to return (), needs to know that it wont return say (2) for example.

So even rest needs to do evaluation.

But explanations say the opposite. That only next does that evaluation, but rest does not, therefore is lazier.

Can anyone explain?

like image 995
tonino.j Avatar asked Apr 28 '26 05:04

tonino.j


1 Answers

user> (def test-seq (lazy-cat [1] [(do (print "Hi!") 2)]))
#'user/test-seq
user> (def rest-test (rest test-seq))
#'user/rest-test
user> (def next-test (next test-seq))
Hi!
#'user/next-test

If rest needed to evaluate an element, you would have seen "Hi!" get printed after I called (rest test-seq). Clearly, rest does not need to do evaluation in order to work.

The reason is that rest does not return () or (2) or anything like that; it returns an unevaluated lazy sequence every time it is called, and the question of whether or not there is anything to return is only answered when that sequence is evaluated later.

like image 114
WolfeFan Avatar answered May 01 '26 17:05

WolfeFan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!