2

Destructuring in Clojure - Part 2

 3 years ago
source link: https://blog.klipse.tech/clojure/2016/03/31/destructuring-part-2.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In a precedent post, we have presented the basics of destructuring in Clojure.

Here, we present a trully amazing way of defining default options for a function, leveraging Clojure destructuring.

The need

Let’s say you want to write a function foo that is very cusomizable, something like 27 optional parameters where each parameter has a default value.

How do you write such a function in Clojure?

Think about it for a few minutes before going on…

Think about it for a few more minutes before going on…

The solution

As it often happens, Clojure provides a simple and elegant solution for this complex semantic problem.

There is a cool :or directive available for destructuring.

We will illustrate it with a simple hello-world function that receives two options: language and upper-case?.

The cool thing is that with one line of code, you create local bindings with default values:

{:keys [language upper-case?] 
  :or {language :en
       upper-case? false}

Pay attention to the way the keys are defined inside the :or directive: the keys are defined as symbols, there are no :!

Enough words!

Let’s see it in action, with KLIPSE (feel free to play with the code, inside the article):

xxxxxxxxxx
(ns my.args
  (:require [clojure.string :as string]))
(defn hello-world [& {:keys [language upper-case?] 
                      :or {language :en
                           upper-case? false}}]
  (let [greeting (case language
                   :fr "bonjour monde"
                   :en "hello world")]
    (if upper-case?
      (string/upper-case greeting)
      greeting)))
(hello-world)
the evaluation will appear here (soon)...
xxxxxxxxxx
(hello-world :language :fr)
xxxxxxxxxx
the evaluation will appear here (soon)...
xxxxxxxxxx
(hello-world :upper-case? true)
xxxxxxxxxx
the evaluation will appear here (soon)...

Clojure rocks!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK