Clojure: rest vs. next

前端 未结 5 2099
执笔经年
执笔经年 2020-12-13 08:03

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 pre

5条回答
  •  忘掉有多难
    2020-12-13 08:39

    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.

提交回复
热议问题