htodfw
Last Updated: February 25, 2016
·
1.09K
· felipeelias
F6faa607e4f541da71fbf8aea6f99a7a

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

Say Thanks
Respond