Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: rest vs. next

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?

like image 330
Daniel Yankowsky Avatar asked Nov 26 '10 20:11

Daniel Yankowsky


2 Answers

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.

like image 112
sepp2k Avatar answered Oct 05 '22 03:10

sepp2k


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.

like image 20
nickik Avatar answered Oct 05 '22 01:10

nickik