Clojure by Example
source link: https://kimh.github.io/clojure-by-example/?
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.
About This Page
I don't like reading thick O'Reilly books when I start learning new programming languages. Rather, I like starting by writing small and dirty code. If you take this approach, having many simple code examples are extremely helpful because I can find answers to these questions very easily.
How can I define a function?
What's the syntax for if and else?
Does the language support string interpolation?
What scopes of variables are available?
These are very basic questions, but enough to start hacking with the new languages.
Recently, I needed to learn this completely new language Clojure but couldn't find what I wanted. So, I decided to create one while learning Clojure.
Clojure is a functional programming language and learning functional programming languages is sometimes hard if you've only had experiences with imperative languages. I have paid careful attention to make this page easy to understand for people who don't have experiences with functional programming languages, so please don't hesitate to read this page even if you don't know anything about functional programming.
Hopefully, this page helps you learning functional programming and starting to write Clojure!
Hello, world!
Our first Clojure code is, of course, printing "Hello, world!". Here, we invoke the function println
with the argument Hello, world!
. We call the invocation of function applying the function to data in Clojure or other functional programming language.
The entire line of the code (....)
is called a form in Clojure. It's also called expression in a general sense, but there is no real problem to use them interchangeably.
You can think of form as something that returns a value. "h"
100
true
are all forms as well.
Bindings
Giving names to values is called assignment in many programming languages. However, we call the mapping between names and values binding in Clojure.
Symbol
Symbols are used to bind names to values. a
b
my-cool-function
nyncat
: they are all symbols in Clojure.
'
will prevent a form from being evaluated. We are doing this here because we want to treat symbols as data in order to pass them to type
function.
If you don't prepend a '
single quote, you are telling Clojure to resolve the symbol. You can obtain bound values by resolving symbols.
When we try to resolve symbols that are not bound to anything, Clojure complains with the exception.
To bind values to names, use let
. Let takes a vector which takes a symbol in the first element and a value in the second element.
You cannot resolve the symbol outside the let. This behavior is very similar to private variable in other programming languages.
You can also provide multiple bindings.
The binding will be immediately available, so each binding can see the prior bindings.
Scope
When Clojure tries to resolve a symbol, the resolution will be done in the scope of the symbol.
Clojure tries to evaluate a
because it needs to pass the value to println
. a
is bound to "aaa"
, so "aaa" is printed in your terminal. Very straight forward.
Now, let
are nested. Like previous example, Clojure tries to resolve a
. However, this time Clojure resolves a
to "AAA"
, instead of aaa
. Each let
will create a scope and symbol resolution is done inside the let where the symbol is resolved.
Also notice that the inner let
does not override the scope of outer let
.
This kind of scope is called lexical scope. For those whom English is not your first language, lexical means words in a sentence. The scope is lexical because the compiler relies on the physical location of the symbol (word) in a program (sentence) to resolve them.
The resolution look up bubbles up until it finds the binding. The inner let
doesn't provide the binding for a
, so it bubbles up to the outer let
. This happens because the scope of inner let is wrapped by the scope of outer let
.
Clojure complains with Unable to resolve symbol exception when it cannot find the binding inside the given scope.
You probably find the idea of lexical scope very familiar. This is because most modern programming languages use lexical scope. There is also something called dynamic scope but you probably don't have to know that right now.
You can also bind symbols to values with def
. While you can access the symbol only from within the let
where it's declared , you can access the symbol declared with def
from anywhere.
You can also override the one already declared later.
The rule of thumb in Clojure is avoiding the use of def
as much as possible. def
introduces state and abusing state will make our code difficult to maintain.
Functions
To define a function, use defn
.
The first argument is the name of function say-hello
, the second argument is the argument of the function [name]
, and the third argument is the function body (println (str "Hello, " name))
.
You can also add documentation.
Use doc
to read the documentation.
You can also add metadata of the function.
You can expand the metadata with meta
. Notice that say-hello
is first passed to var
. This is because meta
expects it's argument to be var object, not value, and var
will turn the passed symbol into var object.
#'
is the reader macro for var
and works the exactly same.
Anonymous Function
Functions are first class objects in Clojure. When you say something is a first class object in programming language X, it means that you can do all the basic operations with the object such as passing it to a function, returned from a function, and binding it to a variable, etc.
To create a function object, use fn
.
You can bind functions to var just like other values. This works just like defn
#()
is the shortcut for fn
.
%
will be replaced with arguments passed to the function. When the function takes multiple arguments, %1
is for the first argument, %2
is for the second and so on.
You can also pass a function to another function. We define two functions and bind to say-hello
and say-bye
vars. We also define a generic function and bind to greeting
.
Then we pass say-hello
and say-bye
to greeting
.
Closure
When a function (let's call this inner function) is returned from another function (let's call this outer function), and the inner function does somethings with the arguments given from outer function, then the inner function is called a closure.
We define a function called inner
. inner
function prints from-outer
var which is supposed to be given by the outer function.
We also define two functions, outer1
and outer2
. These functions both call inner
but with different arguments.
As a result, even if the from-outer
var doesn't change, inner
prints different things.
Namespaces
Namespace provides a way to organize different Clojure objects into to logical groups. These logical groups often are called library and can be used from other namespaces. A namespace is constructed of symbols chained by .
. clojure.core
, clojure-http.client
, my.app.example
: they are all namespaces.
Create-ns
To create a namespace, use create-ns
. However, it is rare to create a namespace with create-ns
because there is more handy ns
macro which will be explained later. You need to place a single quote before a namespace in order to stop resolving the namespace symbol. See Quotes for more details about quoting.
In-ns
To move to a specific namespace, use in-ns
.
Require
One of the important roles of namespace is providing a scope for Clojure objects.
Things that you define in a namespace is not visible from other namespaces by default. As you can see in this example, favorite-language
function is not visible from user
namespace.
To load other namespaces, use require
. Once you load clojure.by.example
namespace, favorite-language
will be available from user
namespace.
Sometimes you want to give a different name to a loaded namespace. In such a case, you can surround the namespace by a vector with :as
keyword.
You can also require multiple namespaces at once.
Refer
You probably don't want to type clojure.by.example
everytime you want to call favorite-language
function. You can avoid this if you use refer
.
require
loads a namespace and refer
refers the namespace. To do these at once, you can use use
.
Import
To import a namespace of Java, you need to use import
. Please see Java section for more information about how to use Java.
ns
macro creates a new namespace and gives you an opportunity to load other namespaces at the creation time.
ns
can take :require
, :use
, and :import
keyword. They work the same way as the corresponding functions explained above except you don't need to quote.
Control Flow
if
takes a predicate (true
or false
) as the first argument. The second argument will be evaluated if the predicate is evaluated to true
. The third argument is equivalent to else in many programming languages which is evaluated when the predicate evaluates to false
.
In Clojure, you can only pass one expression to a branch of if
. However, you often need to pass more than one expression in real programs. In this case, use do
.
If-Let
After testing condition, you often want to use the result of the testing later. if-let
binds the evaluated condition to var when it's truthy. In this example, when positive-number
receives a collection which contains positive numbers, the result of (not-empty (filter pos? numbers))
will be bound to pos-nums
.
pos-nums
is returned since the collection contains positive numbers 1 2
.
The second argument is for else branch. It will be evaluated when the first argument is evaluated to be false.
Note that filter
returns an empty sequence when no value matches the condition instead of nil
and an empty sequence is not falsey in Clojure. But, in order to reach the else branch of if-let
, pos-nums
has to be nil
. For this reason, we are using not-empty
which properly returns nil if the sequence is empty.
When you only care about the case when the condition is truthy, you can use when
. when
is similar to if
but does not contain an else branch and is already wrapped by do
, so you can pass multiple expressions.
Since there is no else branch, this doesn't do anything.
When-Let
There is also when-let
which is similar to if-let
but does not contain an else branch.
There is also case
which works pretty much the same as the one in other programming languages. case
compares the value with each condition with =
and evaluates the expression in the matched branch.
The expression in the last branch will be evaluated if none of the conditions are matched.
When you want to do similar thing to case
but want to write your own test case rather than =
, you can use cond
. You can write a different test case in each branch with cond
.
You use :else
keyword for the default case.
Condp
You can use a predicate with condp
for condition. In this case contains?
is the predicate.
(contains? #{1 2 3} 2)
will be evaluated in this case.
(contains? #{1 2 3} 5)
will be evaluated falsey, thus the default branch will be evaluated.
Boolean
true
and false
are values of Boolean type just like in other programming languages.
In Clojure, everything except false
and nil
are true
.
Strings
Literal
You can create a string by double-quoting text.
To concatenate strings, use str
.
+
operator doesn't work to concat strings against your expectation.
Clojure doesn't have string interpolation. str
works for you.
Format
Like many other languages, Clojure supports string formatting with format
function. The concat example above can also be achieved by using format
function.
The first argument tells format
function the format you want to apply to your strings. %s
is called format specifier and it specifies the type of data to be formatted. The rest of arguments will replace format specifiers.
%s
is a format specifier for string.
%d
is a format specifier for integer.
%.Nf
is a format specifier for floating numbers where N specifies how floating points to print.
%b
is a format specifier for boolean.
Integers
Addition
Subtraction
Multiplication
Division
Interesting thing is that fractions are represented by ratio.
Modulo
Get modulus with mod
Get the greatest number with max
.
Get the smallest number with min
.
Power
Clojure doesn't provide built-in function for exponential operation.
Define a function power
. reduce
takes a sequence generated by repeat
and compute *
against each element of the sequence and returns the sum. The sum is used to do *
against the next element of the sequence.
Bigint
You can use bigint
to handle really big numbers.
N
is a literal for bigint.
Lists
Lists are the most basic collection in Clojure which is a dialect of Lisp (List Processing language). However, you don't often use list as data collection because you have more useful collection data types in Clojure such as vectors or maps.
Literal
A list is a simple collection of values. You can create a list by grouping values with parentheses and a single quote '
at the beginning.
We need '
to prevent the list from being evaluated.
To add a value to the list, use conj
(conj[oin]). Note that the new value is added to the top.
How can I remove elements?
You may wonder: How can I remove an element at a specific position from a list? How can I remove all elements that match in a list?
Unfortunately, there is no built-in function that do these removal operations in lists. You can still use functions from the seq library such as remove, filter, or drop.
If you are not familiar with the seq library, jump to Sequences to learn more!
To get a value from the list, use nth
with it's index number. Index starts from 0
Count
To count how many values are in a list, use count
.
Vectors
You can think of vectors as a more efficient and useful version of lists. It's more practical to store multiple values in a vector.
Literal
You can create a vector by grouping values with square brackets. Unlike lists, you don't need '
because vectors will not be evaluated.
To add a value, use conj
(conj[oin]). Note that the new value is added to the end while it is added to the beginning in lists.
How can I remove elements?
The same story as lists.
To get a value from the vector, you need to specify the index of the value.
Vectors have convenient functions to access elements. To get the first and second elements, use first
and second
.
.indexOf
You can get the index of a value with .indexOf
. The dot before indexOf indicates Java interop to access methods in Java.
Returns -1
if the value doesn't exist.
Sets are collections of unique values. In other words, you cannot have duplicated values in a set.
Another important trait of sets is that the order of values is not guaranteed.
Literal
You can create a set by grouping values with #{}
. Notice the order of the values is not maintained.
You will get an exception when you try to store duplicated value. In this case, 3
is duplicated value.
To add a value, use conj
(conj[oin]).
Because sets doesn't allow duplicated values, you will see only one 4
in the final set.
To create a set where a value is removed (basically removing a value from set), use disj
(disj[oin]).
If trying to disj
a value that doesn't exist in the set, it returns the original set.
Sets are unordered collections of values, meaning that the order of values is not guaranteed. To get a sorted order, use sort
.
Contains?
To check if a value is contained in the set, use contains?
.
Subset?
To check if a set is the part of another set, use subset?
.
Superset?
To check if a set includes another set, use superset?
.
Maps are key-value data structure to store multiple values.
Literal
You can create a map by grouping values with {}
. Although you can use most of Clojure data type as keys, the two most common type of keys are keyword and string.
To get value from key, use get
.
You get nil
when key doesn't exist.
You can specify a default value in the third argument which will be returned when the key doesn't exist in the map.
When the key of a map is keyword, you can use the keyword just like a function to get the value.
Assoc
To add a key-value pair, use assoc
.
If the key already exists, it replaces the value.
Merge
To combine two maps, use merge
.
To get all keys from a map, use keys
.
To get all values from a map, use vals
.
Sequences
Sequences are data types that store multiple values. You may wonder: What are differences from lists or vectors? Why Clojure has so many different collection data types?!
Yes, you can use lists and vectors to store multiple values. In fact, lists and vectors are sequences, and other collection data types such as maps or sets are also sequences.
Sequences are data types that abstract all more concrete data types with unified functions. These functions are called the Seq library in Clojure.
One virtue of the sequence is that you can call the same function to collections without worrying about what types of collections that you are dealing with.
Let's take a look at examples of using map
to different types of collections.
Applying map
for the vector.
Applying map
for the list.
Applying map for the set.
Applying map
for the map. We are using key
function in this case because inc
doesn't work with the map.
When you can apply functions of the seq library to a data type, we say the data type is seqable. The examples above work because lists, vectors, sets, and maps are all seqable collections.
We will see more functions in the seq library in the following sections to get familiar with sequences.
To construct a sequence, use seq
.
seq
takes one seqable collection and converts to a sequence.
The collection data types such as lists, vectors, sets, and maps are all seqable, therefore you can pass any of them to seq
.
Converting a list to a sequence.
Converting a vector to a sequence.
Converting a set to a sequence.
Converting a map to a sequence.
Seqable data types and seq
are what make sequences elegant in Clojure. As long as your data types are seqable, seq
will convert the data to a sequence.
This is why you can apply the same functions in the seq library to different collection types transparently. These seq library functions internally convert passed collection to a sequence and do the right things for you.
You may wonder that returned values look like lists in REPL. However, this is just a matter of displaying and they are actually sequences.
It's clear that it's a sequence if you use type
.
First
To get the first element from a sequence, use first
.
You probably have used first
with different collection data types before without knowing first
is actually a sequence function.
Getting the first element in the vector.
Getting the first element in the vector.
You can call first
with any collection data types (string is a collection of characters) and get expected behavior because first
is a sequence function and all of these data types are seqable.
To get all elements except the first one from a sequence, use rest
.
Here we can see another important trait of sequences: sequence function always returns a sequence no matter of what types of collection it takes.
type
tells you the type of data. As you can see, the vector becomes sequence (CheckedSeq is a type of sequence) once it goes through rest
function.
To add an element to the head of sequence, use cons
.
The operation is equivalent to construct a new sequence by adding an element to the existing sequence, therefore cons
(cons[truct]).
Concat
To combine sequences, use concat
.
You can also pass more than two sequences to concat
.
To apply a function to each element of a sequence, use map
.
If you want to do something more complex with each element, you can pass an anonymous function where each value is bound to x
.
Reduce
reduce
boils down elements in a sequence into a single value by applying a function.
The way reduce
works is that it first takes out the first two elements from the sequence and apply the function to get a result. Then applying the same function to the result with the third element and keeps doing the same until the end of the sequence. Because of this nature, the function must take two arguments.
Otherwise, you will get an exception (inc
is an one argument function)
Of course, you can pass an anonymous function to do more complex stuff. Just don't don't forget that the anonymous function must take two arguments.
If you don't want to start with the first element of the sequence, you can pass a starting point in the second argument.
To insert all elements of a sequence into another sequence, use into
.
Inserting all elements of the list into the vector.
Because of the nature, into
is frequently used to convert from one collection type to another.
Converting a list to a vector.
Converting a vector to a list.
Converting a vector to a set.
Converting a set to a vector.
Converting a nested vector into a map.
Converting a map to a nested vector.
Reverse
To reverse a sequence, use reverse
.
Iterate
You can get a sequence of infinite integers with iterate
. Be careful, though. Running this example will freeze your terminal since the evaluation of this expression never returns.
Range
To generates a sequence of numbers between two points, use range
.
You can get integers by every x within the range. In this case, we get a sequence of integers at every 5.
Repeatedly
To repeat something over and over again, use repeatedly
. We are passing an anonymous function (fn [] (println "hi!"))
because the second argument must be a function.
Doseq
Clojure doesn't have for
or for-each
. Do something to each element of a sequence, use doseq
.
You can bind multiple values. In this case, each element in the first vector is added to each element of the second vector.
To get the first n
elements from a sequence, use take
.
Take all elements from a sequence if the size of the sequence is smaller than n
.
Take-While
To get the first n
elements from a sequence as long as the condition is satisfied but stop taking when the condition is not met, use take-while
. neg?
returns true for negative number.
Note: Taking elements that only satisfies the condition is not what take-while
does. That's the job of select
.
drop
is probably the most primitive way to remove elements from a sequence. drop
will remove the first n
elements.
Drop-While
To get the first n
elements from a sequence as long as the condition is satisfied but stop dropping when the condition is not met, use drop-while
.
Filter
You can remove elements that match the rule you specify from a sequence with filter
.
Here is an example to remove positive numbers from a sequence. In this case, being a positive number is the rule that you specify.
The rule is called predicate. Predicates are functions that return boolean values such as pos?
.
You can construct your own predicate with anonymous functions. In this example, we are removing elements that are 2
.
Remove
You can remove elements that matches a predicate with remove
. The difference from filter
is that returned value is what's removed.
In this example, we remove positive numbers from a sequence. The returned values are negative numbers.
Partition-by
To split a collection and group together in a certain way, or in other word partition, use partition
. In this example, we partition the vector into two groups: one smaller than or equal 3 and another bigger than 3.
Notice that (1 2 3)
at the end of the sequence is grouped together as a separate sequence from the first one. partition-by
doesn't merge values.
Group-by
group-by
splits a collection and does merge them together unlike partition-by
. group-by
returns a map where key is the result of the grouping condition.
Lazy Sequence
Most of Clojure's sequences are lazy. All familiar functions such as map
range
reduce
etc returns lazy sequences.
(iterate inc 0)
generates a sequence of infinite numbers which, of course, takes infinitely. But, you see println
starts printing the numbers (0 1 2 3 ......
. If the generation of the sequence never ends, how println
can even start printing these numbers?
This is possible because iterate
generates lazy sequence and println
is able to handle lazy sequence correctly. println
asks a number to print from iterate
one by one, rather than asking the entire sequence. iterate
only computes numbers as it is requested and pass the numbers to println
.
take
only asks the first n
values from lazy sequence. iterate
also only computes the first five numbers because that's what asked by take
.
If you are looking for how to write a loop in Clojure, I'm sorry, but this is not what you are looking for. Clojure doesn't have an imperative loop because there is no mutable local variable in Clojure. Please see the loop section for more information.
In Clojure, for
is list comprehension. What is list comprehension? First of all, let's look at an example.
for
takes a vector of one or more collections and iterate over collections while binding each value to symbols.
In short, list comprehension is a way to create a list from existing lists. The idea of list comprehension comes from the world of math. It's used in order to write sets in simpler and easier way.
For example, {x | x >0}
means the set of all x
that is bigger than than 0. So if x
is the set of -1, 1, and 2, then the notation refers to the set of 1 and 2 but not -1.
This is a list comprehension that means the same thing as {x | x >0}
in math.
:when
modifier evaluates the body only for values where the predicate is true.
let
modifier can be used to bind intermediate values.
while
modifier stops the evaluation of the body when the predicate is false.
for
iterates collections in a nested fashion. It's useful to create a combination of all elements in given collections.
Recursion
Function is recursive when the function calls itself inside it's definition. This is the most simple way of doing recursion.
We will start from the example of fibo-recursive
function that computes Nth Fibonacci number in the Fibonacci sequence because writing function that computes the Fibonacci numbers is a recursive programming version of hello world.
The Fibonacci sequence is consisted of numbers characterized by the fact that every number after the first two is the sum of the two preceding ones. 0 1 1 2 3 5 8 13 ....
are the beginning of the sequence.
As you can see, we are calling fibo-recursive
function inside the function body of fibo-recursive
function. Calling the function inside the function body is the most basic way to do recursive programming in Clojure and many other programming languages.
Recur
The simple recursion, calling itself inside it's definition, is not the only way to make recursive function in Clojure. recur
is a handy tool to do recursion.
We can write a Fibonacci function by using recur
as well. recur
re-binds it's arguments to new values and call the function with the new values.
Here is another example of the use of recur
. It will keep calling count-down
function with updated arguments until n
becomes 0.
Why do we have recur
when you can write a recursive function with the simple recursion like we do in fibo-recursive
? One of the most important reasons is the performance optimization.
You cannot compute large Fibonacci number with fibo-recursive
. When you try to do that, you will get StackOverflowError.
This is because, with simple recursion, each recursive call creates a stack frame which is a data to store the information of the called function on memory. Doing deep recursion requires large memory for stack frames, but since it cannot, we get StackOverflowError.
Although we don't go deeply into details, one of techniques to avoid this problem is making your function tail recursive. A function is tail recursive when the recursion is happening at the end of it's definition. In other words, a tail recursive function must return itself as it's returned value. When you use recur
, it makes sure you are doing tail recursion.
In fact, you will get an error when you try to call recur
not at the end of a function.
Because recur
does tail recursion, you don't get StackOverflowError with big Fibonacci number although it takes very long time to compute.
Does Clojure have for/while loop? No, Clojure doesn't provide a way to write an imperative loop because there is no mutable local variable in Clojure. However, you can use loop
to write code that works like an imperative loop.
Hopefully, this code looks similar to a simple counting loop in non-functional programming languages you've had experienced with before. In this example, recur
increments count
at the end of each loop and loop
uses it in the next loop.
loop
is always used with recur
and provides a recursion point for recur
. A recursion point is a function entry point that recur
can go back to do recursion. However, recur
doesn't necessary need loop
to do it's job as long as a recursion point is provided.
You can rewrite count-up
function without loop
. In count-up-no-loop
, the recursion point for recur
is the function itself. Note that recur
takes two arguments now. This is because the number of arguments of recur
must match that of it's recursion point function.
One final note: loop/recur
is merely a friendly way to write recursion code. All imperative loops can be converted to recursions and all recursions can be converted to loops, so Clojure chose recursions. Although you can write code that looks like an imperative loop with loop/recur
, Clojure is doing recursion under the hood.
Macros
Clojure's Macros gives you the power to restructure your Clojure code as you like. For example, you can create your own code syntax, invent new control flow, new types of values, etc.
Defmacro
To define a macro, use defmacro
. Like function, you can give it a name, docs, and arguments. Note that you are using quotes '
followed by if
and not
.
This is because you don't want them to be evaluated when you define the macro.
Without quotes, you will see an exception.
Macroexpand
Macros are replaced with Clojure code before it's evaluated. To see how it will be replaced without actually evaluating the macro, use macroexpand
.
Note that you have to use '
because you want it to be unevaluated list.
Quotes
Without a quote, this expression will be just evaluated and returns the value.
However, when an expression is surrounded by quote
, it does not evaluate the expression but returns the expression itself.
'
is another form of quote
. It does the exactly same thing with quote
. '
is used more often than quote
since it's concise.
You can see quoting at work in macros. In this unless
macro, you need to use '
followed by if
and not
because you don't want them to be evaluated inside the macro definition.
Another common place where quote is used is when loading a namespace.
You need to quote clojure.string
namespace otherwise Clojure tries to resolve the namespace symbol and get error. This is because resolving symbol is the default treatment but clojure.string
symbol is not bound to a value.
Syntax-Quotes
Syntax quoting `
works very similarly to quoting '
: it returns an unevaluated expression.
However, you see the difference from quoting when the expression contains symbols. Unlike quoting, syntax-quoting returns the fully qualified namespace. Using fully qualified namespace is very important in order to avoid name conflicts when defining macro.
Unquotes
You will see another difference between syntax quoting and quoting when syntax quoting is used with unquoting ~
. Syntax quoting allows unquoting to evaluate the expression followed by ~
.
Quoting doesn't allow unquoting to evaluate an expression.
Unquote-Splice
The ~@
unquote splice works just like ~
unquote, except it expands a sequence and splice the contents of the sequence into the enclosing syntax-quoted data structure.
Threading Macros
Threading Macros are macros that helps you to write nested forms in a cleaner and more readable way. Despite it's name, threading macros are nothing to do with threads in the parallel computing.
->
->
is called thread-first macro. It's first because it's passing down the evaluation of former forms to the first argument of preceding forms.
Suppose if you want to start from an empty vector and adding numbers to the vector one by one. Here is nested version of the code.
As you add more numbers, the nesting gets deeper and makes your code harder to read. The thread-first macro solves this nesting problem.
Here is the same code with thread-first macro.
The first argument is the initial value that you want to start from. After the first argument is evaluated, it is then passed to the first argument of (conj 1)
. This is equivalent to (conj [] 1)
. The evaluated value is then passed to to the first argument of (conj 2)
. This is equivalent to (conj [1] 2)
. Finally, we are evaluating (conj [1 2] 3)
which returns [1 2 3]
.
->>
->>
is called thread-last macro. It's last because it's passing down the evaluation of former forms to the last argument of preceding forms.
map
is an example of such function that takes a collection in the last argument and apply the function in the first argument.
This code converts country names to upper case and say hello to the countries. The vector of country names are passed to the last argument of the first map which is equivalent to (map clojure.string/upper-case ["japan" "china" "korea"])
. Then it's passed to the second map which is equivalent to (map #(str "Hello " %) ["JAPAN" "CHINA" "KOREA"])
.
Remember that #()
is another way to write a anonymous function.
Delays
Delay
When you want to defer the evaluation of an expression, use delay
.
This is the example of immediately evaluating an expression. Nothing special is involved here. (do ...)
is executed immediately and it's return value is bound to later
var.
When you use delay
, the expression is not evaluated immediately, so "Adding" is not printed.
Force
To evaluate and obtain the result of a delayed expression, use force
.
You can achieve the same thing by using an anonymous function and def
. Then, why do we get bothered with delay?
The difference from a plain function is that delay is only evaluated once and caches the result. "Adding" is only printed once because delay returns cached result from the second time.
Futures
Future
"hello" is printed after sleeping 3 seconds. This is very obvious because these lines of the code are executed synchronously.
If you use future
, (println "hello")
is evaluated immediately, and after three seconds, (println "after sleep")
will be evaluated.
This is because Clojure puts the expression grouped by future
into another thread and moves the current thread forward.
Calls inside future still blocks. So, in this case, "after sleep" is printed after 3 secs.
Deref
future
can return values.
See the returned value #<core$future_call$reify__6320@142cbba: 2>
which is not what you want. This returned value is the current state of the future, not the returned value of (inc 1)
To obtain the returned value of (inc 1)
, you need to dereference the future with deref
.
You can also use @
to dereference a future.
When you dereference a future, you will block until the result is returned.
You can tell deref
how long you want to wait along with a value to return if it does time out.
Finally, you can do a useful thing by combining future
and deref
. You can run multiple time consuming tasks in different threads and block until they finish.
Realized?
To know if a future is already done, use realized?
.
realized
returns true after 5 seconds.
Promises
Promise
When you want to defer the evaluation of expressions until you obtain values to pass to them, use promise
. The easiest example why you want to use promise is implementing a callback.
First, you make a promise with promise
.
Creating a listener that listens to the promise and fire the callback when a value is delivered to the promise. Just like future, promise will block when you dereference it.
Defining a job that takes 5 seconds to finish.
Now let's start the listener and wait for the time consuming job. After being blocked by the dereference of @my-promise
for 5 seconds, you will see the callback is fired.
Atoms
You've might hear this statement before: there is no state in Clojure. Thus, the language is impractical and cannot be used to build real applications. However, this is not true. Clojure has built-in mechanisms to manage application state. Atom
is one of the mechanisms.
Use atom
to create an atom that points to a value. You can create an atom of any values.
To obtain the value of an atom, use deref
or @
.
Reset!
You can set the value of an atom with reset!
. It is used when you are setting the value without regard for the
current value, normally the first time you create the atom.
Atoms are mutable, so you can update as many times as you want.
Swap!
swap!
allows you to use a function to update the value of an atom.
The function that you pass to swap!
will take an argument which is the current atom.
The atom is updated by the return value of the function.
You can pass a function that takes multiple arguments. The first argument of the function is the current atom.
Thread Safety
Atoms are very similar to mutable variables in other programming languages. You can assign value to an atom and update anytime you want. However, Clojure's atom has one big advantage over them: it's thread safe
.
This will update x
ten times and increment x
by 1 every time. The final value of x
will be 10.
Similarly, this will update x
ten times and increment x
every time like the previous example. However, with this code, (def x (inc x))
will be executed in parallel on different threads because we are using future
. When you do this, the final value of x
will not be deterministic anymore. Sometimes it is 5, and sometimes 9 because each thread access and update the same x
in its own timing.
Now atom comes to rescue. x
is atom and we use swap!
to update the value. Unlike vars, atom is thread safe, so x
will be updated by one thread at one time. Thus, the final value of x
is guaranteed to be 10. This is achieved thanks to the Clojure's use of compare-and-swap in atom.
While Atom
is handy to manage a state in a consistent way, Ref
allows you to manage multiple states while ensuring they are consistent.
To create a ref, use ref
.
To obtain the value of a ref, use deref
or @
.
Do-sync
The update of refs must be done inside dosync
block. dosync
is telling Clojure where the transaction update starts from. To set a ref to a new value, use ref-set
.
Any updates to refs always has to be done inside dosync
in order to make transactional updates. Otherwise, Clojure complains with No transaction running
exception.
Alter
alter
allows you to use a function to update the value of a ref.
The function that you pass to alter
will take an argument which is the current ref.
The ref is updated by the return value of the function.
You can pass a function that takes multiple arguments. The first argument of the function is the current atom.
Transaction
This piece of code demonstrates how transaction works.
Suppose we are trying to create an user record in database. Each alter
tries to update user-record ref with user info and you want the ref to be updated only when both alter
succeed.
But, let's assume something wrong occurs between the first and the second alter.
As you see, the user-record ref is still empty. This is because alter
inside dosync
doesn't update the ref until getting out of dosync
block successfully.
This is the atom version that doesn't work. As you see, user-record atom is half updated when there is the exception.
The other way to see how transaction works is trying to observe the value of ref outside dosync block.
We use future to run the whole transaction in the separate thread and wait two seconds before exiting the dosync block.
The value of the ref is still 0 at this moment because the update to the ref is still not committed.
One of the great traits of Clojure is that you can use Java code from your Clojure code. This trait is called Java interop. Although Clojure has very rich standard libraries, sometimes you cannot find libraries that you need to solve your problems. If the library exists in Java, you can borrow it from your Clojure code.
Instantiation
You can create an instance with new
which takes class name as first argument.
The rest of arguments are passed to the constructor function.
There is also .
form available. .
must be placed at the end of class name.
You can also bind Java's instance just like Clojure's value.
Method invocation
Clojure doesn't provide an exponential calculation function in the standard library, so let's borrow pow
method from Math
class.
You can call Java's method just like Clojure's function. Here is how to call pow
class method of Math
class. The class method invocation takes a form of (Classname/Method)
.
The instance method invocation takes a form of (.MethodName Instance Args)
. This example is equivalent to current_date.toString()
in Java.
There is also .
form available.
If you want to call a method that takes arguments, you can pass them after an instance. This example is equivalent to date1.equals(date2)
in Java.
Many Thanks
CLOJURE for the BRAVE and TRUE
And many other great articles and pages made by the Clojure community.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK