Clojure variadic map

When begining with Clojure, little by little you find out some snipets of code that enlighten and clean your code. One example I’ve encountered is when using map in function parameters, e.g.

(defn say-hi [{:keys [first-name last-name title]}]
   (print (str "Hello, " title " " last-name "!\n"
               "May I call you '" first-name "'?\n")))

So that it’s invocation is

=> (say-hi {:first-name "Murray" :last-name "Rothbard"
            :title "Mr."})
Hello, Mr. Rothbard!
May I call you 'Murray'?
;=> nil

But there is a cleaner way of doing it so, with just one “&” away:

(defn say-cleaner-hi [& {:keys [first-name last-name title]}]
   (print (str "Hello, " title " " last-name "!\n"
               "May I call you '" first-name "'?\n")))

Now the function call will be

(say-cleaner-hi :first-name "Murray" :last-name "Rothbard"
                :title "Mr.")
Hello, Mr. Rothbard!
May I call you 'Murray'?
;=> nil

Ain’t that pretty?

Advertisements