I'm having a hard time understanding the difference between rest
and next
in Clojure. The official site's page on laziness indicates that the preference should probably be to use rest
, but it doesn't really explain clearly the difference between the two. Can anybody provide some insight?
As the page you linked described, next
is stricter than (the new behaviour of) rest
because it needs to evaluate the structure of the lazy cons to know whether to return nil
or a seq.
rest
on the other hand always returns a seq, so nothing needs to be evaluated until you actually use the result of rest
. In other words, rest
is more lazy than next
.
It's easy if you have this:
(next '(1)) => nil
So next
looks at the next thing and if the line is empty it returns nil
instead of an empty seq. This means that it needs to look ahead (to the first item it would return) which makes it not fully lazy (maybe you don't need the next value, but next
wastes the compute time to look ahead).
(rest '(1)) => ()
rest
doesn't look ahead and just returns the rest of the seq.
Maybe you think, Why even bother using two different things here? The reason is that you normally want to know if there is nothing left in the seq and just return nil
, but in some cases where performance is very important and evaluating one more item could mean tremendous effort you can use rest
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With