Clojure Journey XII – Short Tip: Multi-arity functions

In our last posts of this series we have been learning everything that we need to create beautiful functions, let, destructuring, and of course, functions. In this post, we’ll talk about a simple but powerful feature, multi-arity functions, an interesting feature shipped with Clojure that among other things, allow us to make “default values” on functions parameters.

Arity can be basically defined as the number of arguments that a function can take. 

Thinking about magic, a great wizard will need to adapt his magic depending on some conditions. Using multi-arity functions, as the name says, you can write a function that accepts a different number of arguments and runs a different branch of code for each.

The syntax is simple, using the already known defn macro that is used to create functions! Just wrap each arity around parentheses.

=> (defn foo
     ([x] (+ x 1))
     ([x y] (+ x y)))
#'user/foo
=> (foo 1)
2
=> (foo 1 3)
4

These kinds of functions are heavily used among Clojure wizards to provide default argument values to its functions, just calling the same function inside a less arity branch of the function, easy right?

=> (defn foo
     ([x] (foo x 1))
     ([x y] (+ x y)))
#'user/foo
=> (foo 1)
2
=> (foo 1 3)
4

Conclusions

A short post talking about a simple but powerful feature of Clojure language that will be used almost all the time in your life as a wizard. Using multi-arity functions we can start creating default arguments to our functions, among many other possible scenarios.

Final thought

If you have any questions that I can help you with, please ask! Send an email (otaviopvaladares at gmail.com), pm me on my Twitter, or comment on this post!

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: