Last Updated: October 04, 2020
·
1.6K
· felipeelias

rest vs next - Clojure

Normally restand next functions behave the same:

(next [:a :b :c])
-> (:b :c)
(rest [:a :b :c]) 
-> (:b :c)

The exception is when the collection is empty:

(next [])        
-> nil
(rest [])
-> ()

next is useful when creating a loop that breaks when the collection is nil:

(loop [m-map {}
       m-keys [:a :b :c]
       m-vals [1 2 3]]
  (if (and m-keys m-vals)
    (recur (assoc m-map (first m-keys) (first m-vals))
           (next m-keys)
           (next m-vals))
    m-map))

-> {:c 3, :b 2, :a 1}

If you use rest in this case, you'd have to check for empty? in the collection