神刀安全网

Destructuring in Clojure – Part 2

In aprecedent 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: there are no : !

Enough words!

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

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Destructuring in Clojure – Part 2

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址