About

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 functionprintln with the argumentHello, 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"100true 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. abmy-cool-functionnyncat: they are all symbols in Clojure.

You cannot resolve the symbol outside the let. This behavior is very similar to private variable in other programming languages.

user=>(let[l"light"d"darkness"](println(str"God said let there be "l))(println(str"God also said let there be "d)))GodsaidlettherebelightGodalsosaidlettherebedarknessnil

You can also provide multiple bindings.

user>(let[l"light"l_d(strl" and"" darkness")](println(str"God also said let there be "l_d)))Godalsosaidlettherebelightanddarknessnil

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.

user>(let[a"aaa"](printlna))aaanil

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.

user>(let[a"aaa"](let[a"AAA"](printlna)))AAAnil

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.

user>(let[a"aaa"](let[a"AAA"](printlna))(printlna))AAAaaanil

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.

user>(let[a"a"](let[](printlna)))anil

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.

Def

user=>(defobject"light")#'user/objectuser=>(println(str"God said let there be "object))Godsaidlettherebelightnil

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.

user=>(defobject"darkness")#'user/objectuser=>(println(str"God said let there be "object))Godsaidlettherebedarknessnil

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.

user=>(defnsay-hello"Takes name argument and say hello to the name"{:added"1.0":statictrue}[name](println(str"Hello, "name)))

You can also add metadata of the function.

user=>(meta(varsay-hello)){:added"1.0",:ns#<Namespaceuser>,:namesay-hello,:file"NO_SOURCE_PATH",:statictrue,:column1,:line1,:arglists([name]),:doc"Takes name argument and say hello to the name"}

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.

user>(meta#'say-hello){:added"1.0",:ns#<Namespaceuser>,:namesay-hello,:file"NO_SOURCE_PATH",:statictrue,:column1,:line1,:arglists([name]),:doc"Takes name argument and say hello to the name"}

#' 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.

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.

user=>(defninner[from-outer](fn[](printlnfrom-outer)))#'user/inneruser=>(defouter1(inner"this is from outer"))#'user/outer1user=>(defouter2(inner"this is yet another from outer"))#'user/outer2user=>(outer1)thisisfromouterniluser=>(outer2)thisisyetanotherfromouternil

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

user>(create-ns'clojure.by.example)nil

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.

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

user=>(iftrue(println"This is always printed")(println"This is never printed"))Thisisalwaysprintednil

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.

user=>(iftrue(do(println"one")(println"two")))onetwonil

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.

After testing condition, you often want to reuse it later. if-let binds the evaluated condition to var when it’s truthy. In this example, when positive-number-seq receives a collection which contains positive numbers, the result of (seq (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.

user=> (seq [1 2])
(1 2)
user=> (seq [])
nil

Note that seq will return nil when empty collection is passed.

When

user=>(whentrue(println"one")(println"two"))onetwonil

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.

When-Let

There is also when-let which is similar to if-let but does not contain an else branch.

Case

user=>(defncase-test-1[n](casen1"n is 1"2"n is 2""n is other"))#'user/case-test-1user=>(println(case-test-11))nis1niluser=>(println(case-test-12))nis2niluser=>(println(case-test-13))nisothernil

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.

Cond

user=>(defncond-test[n](cond(=n1)"n is 1"(and(>n3)(<n10))"n is over 3 and under 10":else"n is other"))user=>(println(cond-test1))nis1niluser=>(println(cond-test5))nisover3andunder10niluser=>(println(cond-test15))nisothernil

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

user=>(defncondp-test-2[n](condpcontains?n[123]"n is either 1 or 2 or 3""n is not 1 or 2 or 3"))#'user/condp-test-2user=>(println(condp-test-22))niseither1or2or3niluser=>(println(condp-test-25))nisnot1or2or3nil

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

user=>truetrueuser=>falsefalse

true and false are values of Boolean type just like in other programming languages.

user>(let[first"Hirokuni"last"Kim"](str"My name is "first" "last))"My name is Hirokuni Kim"

Clojure doesn’t have string interpolation. str works for you.

Format

user=>(format"My name is %s %s""Hirokuni""Kim")"My name is Hirokuni Kim"

Like many other languages, Clojure supports string formatting with format function. The concat example above can also be archived 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.

Division

Modulo

Max

Min

user=>(min54321)1

Get the smallest number with min.

Power

user=>(defnpower[xn](reduce*(repeatnx)))user=>(power23)8

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.

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

user=>'(123)(123)

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.

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.

Seq

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.

user=>(seq'(123))(123)

Converting a list to a sequence.

user=>(seq[123])(123)

Converting a vector to a sequence.

user=>(seq#{123})(132)

Converting a set to a sequence.

user=> (seq {:a 1 :b 2 :c 3})
([:a 1] [:b 2] [:c 3])

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.

user=>(type(seq[123]))clojure.lang.PersistentVector$ChunkedSeq

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.

user=>(first[123])1

Getting the first element in the vector.

user=>(first"string")\s

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.

Rest

user=>(rest[123])(23)

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.

Cons

The operation is equivalent to construct a new sequence by adding an element to the existing sequence, therefore cons(cons[truct]).

Concat

user=>(concat'(123)'(456))(123456)

To combine sequences, use concat.

user=>(concat'(12)'(45)'(78)'(910))(124578910)

You can also pass more than two sequences to concat.

Map

user=>(mapinc[123])(234)

To apply a function to each element of a sequence, use map.

user=>(map(fn[x](inc(valx))){:a1:b2:c3})(234)

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

user=>(reduce+[1234])10

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.

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

user=>(doseq[animal["cat""dog""horse"]](printlnanimal))catdoghorsenil

Clojure doesn’t have for or for-each. Do something to each element of a sequence, use doseq.

user=>(doseq[n1[12]n2[45]](println(+n1n2)))5667nil

You can bind multiple values. In this case, each element in the first vector is added to each element of the second vector.

Take

user=>(take5(range0100))(01234)

To get the first n elements from a sequence, use take.

user=>(take10(range05))(01234)

Take all elements from a sequence if the size of the sequence is smaller than n.

Take-While

user=>(take-whileneg?[-3-2-10123])(-3-2-1)

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

user=>(drop5(range010))(56789)

drop is probably the most primitive way to remove elements from a sequence. drop will remove the first n elements.

Drop-While

user=>(drop-whileneg?[-3-2-10123])(0123)

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.

user=>(filterpos?[-123])(23)

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?.

user=>(filter(fn[v](=v2))[-123])(2)

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.

user=>(removepos?[-1-234])(-1-2)

In this example, we remove positive numbers from a sequence. The returned values are negative numbers.

Partition-by

user=>(partition-by#(<3%)[123456])((123)(456))

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.

user=>(partition-by#(<3%)[123456123])((123)(456)(123))

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

user=>(group-by#(<3%)[123456123]){false[123123],true[456]}

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 maprangereduce etc returns lazy sequences.

;; You need hit Ctrl+c very quickly to stop!!
user=>(println(iterateinc0))(0123......

(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.

user=>(println(take5(iterateinc0)))(01234)nil

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.

For

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.

user=>(for[x'(123)](+10x))(111213)

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.

user=>(for[x'(-112):when(<0x)]x)(12)

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.

user=>(for[x[012345]:let[y(*x3)]:when(even?y)]y)(0612)

let modifier can be used to bind intermediate values.

user=>(for[x(range10):while(not=x5)]x)(01234)

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.

user>(defnfibo-recur[iteration](let[fibo(fn[onetwon](if(=iterationn)one(recurtwo(+onetwo)(incn))))];; 0N 1N are bigint literals. See Bigint section
;; We need to use bigint to avoid StackOverflow to do the addition of big Fibonacci numbers
;; demonstrated below.
(fibo0N1N0)))#'user/fibo-recuruser>(fibo-recur6)8

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.

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.

user>(fibo-recur100000);; takes very long time to compute

Because recur does tail recursion, you don’t get StackOverflowError with big Fibonacci number although it takes very long time to compute.

Loop

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

user=>(defmacrounless[testthen]"Evaluates then when test evaluates to be falsey"(list'if(list'nottest)then))user=>(unlessfalse(println"false!!"))false!!nil;; Error
user=>(defmacrounless[testthen]"Evaluates then when test evaluates to be falsey"(listif(listnottest)then))CompilerExceptionjava.lang.RuntimeException:Unabletoresolvesymbol:ifinthiscontext,compiling:(NO_SOURCE_PATH:3:12)

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

user=>(+12)3user=>(quote(+12))(+12)user=>'(+12)(+12)

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.

user=>(defmacrounless[testthen]"Evaluates then when test evaluates to be falsey"(list'if(list'nottest)then))

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.

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

user=>`(+12)(clojure.core/+12)

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.

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.

user>(conj(conj(conj[]1)2)3)[123]

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.

user>(->[](conj1)(conj2)(conj3))[123]

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"]).

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.

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

Atom

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.

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.

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 archived thanks to the Clojure’s use of compare-and-swap in atom.

Refs

Ref

While Atom is handy to manage a state in a consistent way, Ref allows you to manage multiple states while ensuring they are consistent.

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.

Java

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

user> (new java.util.Date)
#inst "2017-01-15T08:04:14.983-00:00"

You can create an instance with new which takes class name as first argument.