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!

Clojure Journey XI – Let

In the last post of our Clojure Journey series, we learned how to create functions, a powerful way of organize our code, dividing it in small pieces of logic. Just like wizards have their spell book with all kind of magics, we now have our functions, ready to help us solving our tasks.

Knowing how to create functions doesn’t mean that it’ll look beautiful, meaningful and readable, it takes time, but previous experience in others languages can help you in this journey to become a Clojure wizard.

To make your function more readable, in most of cases you’ll need to bind some information to an identifier, what we usually call “variables”, one of the way to do it in Clojure is using def as we already learned before. As example, let’s imagine that we have a function that receives an recently created order (just a simple map for sort of simplicity) and need to send to it’s buyer a confirmation email:

(defn send-confirmation-email [order]
  (send-email (:email (:user order)) 
    (open-file "/example-path/template.html")))

This is the simplest way to do it, you get the information needed and pass it to the supposed send-email. As an experienced wizard, you think that it can be more readable if you extract some information and bind it to an identifier to use it later, so you do it:

(defn send-confirmation-email [order]
  (def user-email (:email (:user order)))
  (def email-template (open-file
    "/example-path/template.html"))
  (send-email user-email email-template))

Good intentions, this code will work, but is not de best way to do it. It’s not a “Clojurist” way.

The reason behind this is that def will create an identifier associated with the current namespace (don’t worry, we already learned about namespaces), that can be globally accessed, something usually called “global variables”, which can lead to a lot of problems when used in the wrong way, other parts of the code non related can start referring to it and create a dependency problem, or it be redefined and break your code.

Let the way to go

To solve this problem Clojure wizards introduced a new magic, called let, using it you can bind value to symbols in a lexical scope, in short, it creates something like a local variable for you, that will only live inside your function.

The syntax is simple to use this magic, just pass a vector containing N combinations of symbol and its binding.

=> (let [x 1
      y 2]
  (+ x y))
3

Pay attention to the lexical scope, x and y will not exist outside let scope, so if you call them outside it, it will not exist.

Let let lexical context
Clojure let lexical context

Using let is good, but using it with functions is even better, and its real power shines, if we refactor our send-confirmation-email using our new knowledge, it will look something like this:

(defn send-confirmation-email [order]
  (let [user-email (:email (:user order))
        email-template (open-file "/example-path/template.html")]
    (send-email user-email email-template)))

Note: While using let, you can refer to variables defined above.

In this way, youll have your variables only in the function scope, without them being available out of the function scope. This is the Clojurist way of deal with local variables.

Wizard happy, now using let our code is much better.
Now using let, our code is much better!

Let also allows us to use destructuring in the same way that we saw when we learned about it:

=> (def vec [:a :b :c :d])
#'user/vec
=> (let [[a b c d] vec]
     (println a b c d))
:a :b :c :d

Clojure also has if-let and when-let methods that can help you a lot with your code, I pretty recommend to read about it!

Conclusions

Let can make your functions more beautiful and correctly, dont forget to use it.

Next steps

On the next post of this series, we’ll still talking about functions, this time talking about multi-arity functions.

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!

Clojure Journey X – Namespaces

Now that we know how to create our functions we need to understand how Clojure organizes and accesses it, this way is called namespaces.

Every good wizard has a lot of books on his bookshelf, with different magics to use in a lot of situations. Imagine a Clojure namespace as being one of your books, and each function or variable (defined with def) is written on it, when you need to use your function, you just search for it in this book and use it!

Your book (namespace) of functions to deal with strings

If you enter in your REPL, you’ll be in a “default” namespace called user, everything that you define here, we’ll be associated with this namespace.

user => (def author-name "otavio")
#'user/author-name

You may have already noticed that when we defined author-name it returned #'user/author-name, it means that you defined an author-name in the user namespace.

To create a new namespace and switch to it, you only need to type ns and a name to it, it will create (if not exists), and you can’t access values defined in other namespace directly anymore. Just like a blank book, waiting to be written.

user => (ns my-new-ns)
nil
my-new-ns => author-name
Syntax error compiling at (REPL:1:1).
Unable to resolve symbol: author-name in this context
Let’s start writing our namespaces

If you want, you can access any variable or function defined in other namespace, just typing its “full address” namespace + name.

my-new-ns => user/author-name
"otavio"

Switch between namespaces is easy, just use in-ns and pass the namespace name preceded by quote. After it, you can access the defined values of this namespace directly again.

any-ns=> (in-ns 'user)
#object[clojure.lang.Namespace 0x56317ffa "user"]
user=> author-name
"otavio"

You can always see in which namespace are you, just typing *ns* (but you can just see in your REPL too.)

Reading other books

Sometimes you as a wizard will want to read books written by other wizards, to not lose your precious time reinventing the wheel creating already existent magics.

Most languages are shipped with a lot of code that you must need, things like string operations, basic http logic, and much more. All this code is available for you, in the form of namespaces, and to use it is simple!

Famous Clojure Libs, just waiting to be used!

Every time that you create a new namespace using ns in your REPL, it will be automatically loaded on it, and you can just start using it, but this is not true while trying to access namespaces packaged in files (which will be important in the future when we start to work with multiple files in large projects).

Let’s use as an example the namespace clojure.string which contains functions to deal with common string operations, we want to use capitalize function from it! The first step is to make our REPL aware of the namespace that you want to use using the require function, passing as an argument the namespace that we want to load in our REPL, after this all functions and symbols globally defined in this namespace are available to us, just use them using its ‘full address’ namespace + name.

user => (require 'clojure.string)
nil
user => (clojure.string/capitalize "hello clojure")
"Hello lojure"

But write clojure.string every time isn’t productive, so we can use the :as keyword to create an alias to use this namespace.

user => (require '[clojure.string :as str])
nil
user => (str/capitalize "hello clojure")
"Hello clojure"

This required namespace will be available only on current namespace, if you change to other namespace, it will no longer be available.

Better now, ya? This is the Clojurist way of using external namespaces from other namespace (including libraries as we’ll see in the future).

If you want, you can also enter in the string namespaces and use functions directly, but I really don’t know why you may want to do it:

user => (require 'clojure.string)
nil
user => (in-ns 'clojure.string)
nil
clojure.string => (capitalize "hello clojure")
"Hello clojure"

Conclusions

Learn how to use namespaces is important! We did not learn how to pack namespace in files yet, but we will in the future! This knowledge is important, it will help while developing using our REPL, and in the future post talking about files.

Next steps

On the next post of this series, we’ll still talking about functions, with just a short trick to make our functions better and readable!

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!

Clojure Journey IX – Destructuring

While creating your beautiful functions you probably will face many times your function receiving a sequential-like structure and needing to decompose its values and bind it to names to use later. For example:

=> (def numbers [42 1 2 3 4])
#'user/numbers
=> (def my-func [any-vector]
     (println (first any-vector) (second any-vector)))
#'user/my-func
=> (my-func numbers)
42 1

You as a critical wizard, may think that’s awful, right? Would be nice if Clojure provides a way of do this process in a beautiful and magic way like in other features right?

This is so awful, we need a way to change it.

Fortunately clojure already provides a way to do it, and its called Destructuring,its the process of bind names to data structure’s values in a readable way.

Many languages have destructuring support like Javascript, Clojure as no exception, has it as feature and don’t require any third party libraries to do so.

A common point of confusion is to think that destructuring is pattern matching, but it’s not, it’s different. To achieve pattern matching in Clojure you can use core.match lib, but it’s topic for another post.

The basics

The most common example as we saw, is to extract things from vectors, imagine that inside your function, you need to bind names to each record of a size 2 vector, you probably will write something like that:

=> (defn print-values [vector]
     (println (first vector) (second vector)))
#'user/print-values
=> (print-values [1 2])
1 2

But you can use destructuring to do it in a less verbose and beautiful way, and it will work just as the first example.

=> (defn print-values [[first second]]
     (println first second))
#'user/print-values
=> (print-values [1 2])
1 2
List destructuring

Please, note that you don’t need to match the full vector, you can match only the first item if you want:

=> (defn print-values [[first-value]]
     (println first-value))
#'user/print-values
=> (print-values [1 2 3 4 5])
1

As in many languages you can use _ to ignore values, in destructuring you can use it to ignore values in the process:

=> (defn print-values [[first-value _ third-value]]
     (println first-value third-value))
#'user/print-values
=> (print-values [1 2 3])
1 3

You can use & to bind the remaining itens of the vector who are not bindend to any name.

=> (defn print-rest [[_ _ _ & rest-itens]]
     (println rest-itens))
#'user/print-rest
=> (print-rest [1 2 3 4 5 6 7])
(4 5 6 7)

Probably you’re thinking that may think that destructuring doesn’t make any sense, but when dealing with nested vectors, its beautiful (and will be much more beautiful when dealing with maps):

=> (defn print-nested [[_ _  [first-nested-value second-nested-value]]]
     (println first-nested-value second-nested-value))
#'user/print-nested
=> (print-nested [1 2 [3 4]])
3 4

Using the bind :as in the last thing of your destructuring you can bind all the struct to a name, just like this:

=> (defn entire-vector [[vec :as entire-vector]]
     (println entire-vector))
#'user/entire-vector
=> (entire-vector [1 2 3 4 5 6 7])
[1 2 3 4 5 6 7]

The beautiful way of dealing with maps

Most of Clojure developers works with web applications, and probably are working with JSON file format, meaning that most of them are working with maps. If you already worked if this kind of application you know that most of your time you’ll be dealing with this hash maps structures, getting data from it.

This brings us to a nice spot, where we can use what we learned from destructuring to extract what we want from a map, representing some received JSON. Let’s take as example, a map that represents a person:

=> (def people {:name "Otavio", 
                :last-name "Valadares",
                :contact {:phone "+550000000000",
                          :email "xpto@xpto.com"}, 
                :address {:country :brazil,
                          :state :sp,
                          :street "Xpto Street",
                          :number "42"}})
#'user/people

If we want, we can just access the number using techniques that we already learned in this post just changing to map, the recipe is to use the syntax {first-symbol :key, second-symbol :second-key}:

=> (defn address-number [{{number :number} :address}]
     (println number))
#'user/address-number
=> (address-number people)
42

But following this syntax of always specifying the symbol and key can be “ugly”, why not use a more beautiful and stylish way? Fortunately, the first Clojure wizards has built a shortcut for us, we only need to use :keys key can be used to only write each key once.

=> (defn address-number [{{:keys [number]} :address}]
     (println number))
#'user/address-number
=> (address-number people)
42

It’s important to note that both lists and maps will be bound nil when the value to destruct doesn’t exist, so, pay attention to it. But a good wizard always has a defense prepared against nil, and when dealing with destructuring, we can use :or keywords to define a default value to some bind. Just put the keyword followed by a map containing the not found key and the default value.

=> (defn get-doc [{:keys [doc] :or {doc"xxx"}}]
     (println doc))
#'user/get-document
=> (get-doc people)
xxx
Lets do some magic to have keywords!

Everything that we can use with lists, we can use with maps too, like :as or & keywords and much more.

Conclusions

Destructuring have many other tricks too, that you can study here. But with this text you already know enough to make your functions looks beautiful, it will look specially useful when we start dealing with JSON data with a lot of nested data.

Next steps

On the next post of this series, we’ll still talking about functions, with just a short trick to our functions.

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!

Follow my blog to get notified off every new post:

Clojure Journey VIII – Functions

Functions are a crucial part of every programmer’s day job, when talking about a function, it can be defined as a set of instructions that MUST perform a specific task together and if you want, can be referred under an identifier.

For those who already know the basics of a programming language, it isn’t a new technique, almost all programming languages have some way to create your own functions. Clojure as a functional programming language, has functions on its core (as the name suggests), a software written using it, can be seen as a set of functions that together perform a task.

A function in a beautiful blueprint can be drawn as a magic black box that receives inputs and produces outputs, for example, we have a black box, that we sent 2 and 2 to it, and the output is 4, therefore, we can conclude that inside that box has a mechanism to sum the given x and y:

In Clojure to create a new function, we can use fn, fallowed by its params inside square brackets, and its body when you place your operations.

To create a function that prints a hello with a given name, we just need to type:

=> (fn [name] (println "Hello" name))

Now we have our function, that’s great! But how do we call it?

Using this way we’re creating what are called “anonymous functions” and this name is given because this function doesn’t have a name to be called later, and if we want to use it, we need to evaluate it and pass its arguments.

=> ((fn [name] (println "Hello" name)) "Gabi")
"Hello Gabi"

In that way, Clojure will evaluate our function first, and then call it with our given arguments.

Anonymous function has a short way of be created to, and its using #(), our previous example will look like this in the shorter way:

(#(println "Hello" %) "Gabriela")

Note that our parameter is referred as % inside our anonymous function in that way, if we have more parameters to our function it can be referred as %1, %2%n, and we can use %& to refer to the “rest”.

If we want to bind an anonymous function to an identifier to refer later, we can use the def that we already learned in past posts, to bind our anonymous function to a name.

=> (def say-hello (fn [name] (println "Hello" name)))
#'user/say-hello
(say-hello "Gabriela")
=> "Hello Gabriela"

This is awesome, now we can use our function how many times we want, with different parameters:

=> (say-hello "Otavio")
"Hello Otavio"
=> (say-hello "V")
"Hello V"

Fortunately, to avoid write def fallowed by fn every time, Clojure has defn that will act as a fusion of def and fn that we previous used:

Our say-hello the function will look like this:

=> (defn say-hello [name] (println "Hello" name))
#'user/say-hello
=> (say-hello "Clojure")
"Hello Clojure"

Now we know a new spell that we can use every time that we’re playing with magic! We can write our “black box” function from the first example, like this:

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

Now every time makes sense right?

This example can lead us to another interesting thing in Clojure, a function will always return its last evaluated instruction, what it means? A function will always return something, our sum function (last example) will return the sum of x and y because (+ x y) it’s our last evaluated expression.

Clojure treats its functions as what we call “first-class citizens” and it means that we can return functions from functions, bind it (store at variable), store it at a data structure, and pass functions as an argument to other functions, that’s great right? Too much power to use while creating new spells.

Functions like our sum that always returns the same value for the same arguments is called pure functions, in a beautiful world, it would be the only kind of functions, we always want to work with pure functions because it’s returned value is predictable. Unfortunately, we have the dark side, “impure functions” which is basically a function that can return different values for the same arguments and can return unexpected values.

Let’s take a look at an example, what of these functions can you always preview the value returned?

The first one just multiply two values, with we send it two numbers it will work, for example, if we call it with 2 and 2 it will always return 4, we can always predict its return value and its awesome, we have a pure function.

The second function of the draw, if impure, the function read-line, will take a input from user, and we can’t predict its return value, the user can input anything when asked, and we can’t preview it.

When writing good software is a good architecture pattern to isolate impure functions, so you can correctly handle it, expecting errors and much more.

Function documentation

When writing software is always good to find a balance when your software is correctly documented, Clojure provides a beautiful way to document part of your software with docstrings on function declarations, just add your doc before function parameters, like that:

(defn sum
  "Sum `x` and `y`"
  [x y]
  (+ x y)) 

When we learn more about namespaces we’ll learn how much it can be useful to document public functions.

You can read a function doc with doc spell, just use it with the function name, if its contains doc, it will be displayed:

=> (doc sum)
-------------------------
user/sum
([x y])
  Sum `x` and `y`
nil

When use anonymous functions

Anonymous functions look good, but some people have the question “If I can create a named function and call it everywhere, why should I need it?”, well, it’s a good question. It can be used in a lot of ways, mostly when dealing with functions that returns or receive functions, or in specific cases when you need to write a short function.

The most common example is with map (that we learned how to use in the previous post), sometimes you’ll want to apply a simple function to a sequence and don’t want to create a named function, for example:

=> (map #(str "Hey " % ", how you doin?") 
     ["Otavio" "V" "Gabi"])
("Hey Otavio, how you doin?" "Hey V, how you doin?" 
"Hey Gabi, how you doin?")

Know when to use short anonymous functions is a great skill for a little wizard.

Conclusions

Functions are essential, especially in a functional language, it’s a core feature in almost all programming languages and is a part of every developer day, learn and understand how to use it will be great and will help a lot when developing.

We as Clojure wizards can create a lot of new, useful and powerful spells now.

Next steps

On the next post of this series, we’ll keep talking about functions, but more features around it that can help you a lot.

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!

Follow my blog to get notified off every new post: