Clojure: rest vs. next

前端 未结 5 2086
执笔经年
执笔经年 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:34

    I now prefer to use next with recursion, as the escape-evaluation is simpler/cleaner:

    (loop [lst a-list]
        (when lst
            (recur (next lst))
    

    vs

    (loop [lst a-list]
        (when-not (empty? lst)   ;; or (when (seq? lst)
            (recur (rest lst))
    

    A case for using rest, though, would be if you use a collection as a queue or stack. In that case you want your function to return an empty collection when popping or dequeueing the last item.

提交回复
热议问题