rest vs next - Clojure
Normally rest
and 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
Written by Felipe Elias Philipp
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Clojure
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#