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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s