Functional Advantage with Clojure

John Stevenson


Why Funcitonal Programming?

Helps you think differently

"New" tools to solve "new" problems

Functional Programming is part of modern languages

Functional Programming Languages

The Classics

  • Haskell, ML, Common Lisp, Scheme, etc

The JVM Stack

  • Clojure, Scala, Java 8 (lambdas)

Other examples

  • Python
  • JavaScript (ECMAScript 6)

Why Clojure

Simple, Powerful, Fun

Why not other functional languages ?


The pure approach makes Haskell a harder language to make it useful

Very academic approach to the language, evolving to become more Practical

Strong focus on Types


An immutable approach is not strongly supported by the language, yet

Usually written in a way that is hard to maintain

  • Functional JavaScript can be so much more readable


A great language to learn programming

Lots of really good libraries

So why has this not been more widely adopted?

What is Clojure?

General purpose Functional programming language on the

  • Java Virtual machine (JVM)
  • Google Javascript V8 engine (ClojureScript)
  • Microsoft Common Language Runtime (CLR)

A modern LISP

A powerful way to solve problems

LISP is the 2nd oldest language still used in production

Clojure is a modern dialect of LISP

Who is using Clojure

UBS Classified
CitiGroup Financial Trading
Netflix Map-Reduce Languges for writing Apps for Hadoop Pig
Large Insurance company Rebuild policy management system
USwitch Creating meaningful data from multiple sources
Daily Mail Runing the high volume site Mail Online
Xively IoT
Masterdon C Data centre analysis (Incanta, Storm)
Thoughtworks Rapid development for clients
LinkedIn Aspects of their social graph
Meta-X Performance art (Overtone, Quil)

London Clojurians Jobs

Lets explore Clojure further

See Clojure Through Code for lots of example code

Iterate faster with Clojure

Dynamic nature of Clojure is perfect for discovering the real needs of the business

"REPL Driven Development"

Dynamic environment

  • Evaluate code in place
  • Use the REPL to quickly iterate on ideas

– No obvious compile cycle, no compile tea break

Dynamic Typing

Type Inference does the heavy lifting

No need to battle an every changing object model

Data driven design

Flexible data structures form the knowledge of the application

Functions act on those data structures without side effects (unless you want them)

Simple Java Interoperability

Clojure apps packaged as Java Jar (UberJar)

Import & use Java libraries (any JVM languages)

Call Java easily

. new throw try

Dynamic Runtime option

Dynamic compilation allows code changes to be injected without restarting your application

Simple Clojure syntax

Really quick to get coding

  • define data structures (the data)
  • define functions (the behaviour)
  • call functions (which always return a value)

Simple Clojure program

Defining a namespace, data structure & function, then calling the function.

(ns jr0cket.demo)

(def my-data [1,2,3, frog])

(defn do-stuff [parameter]
  (str parameter))

(do-stuff my-data)

Data Structure Driven Design

Define a meaningful data structure

Define the functions (behaviour) that work with that data

"It is better to have 100 functions operate on one data structure than to have 10 functions operate on 10 data structures" - A.J. Perlis

Data Structures

Persistent data structures in Clojure:

  • List
  • Map (HashMap, Key-Value pairs)
  • Vector (Array)
  • Sets (Unique values)

Typical data structures are maps, vectors, maps of maps, vectors of vectors, etc

Mixing data structures all together

(def data {:keyword1 value1 
           :vector [1 2 3]
           :map {:a 1 :b 2 :c cat}}
           :mixed {:vector [1 2 3 fish]
                     [1 2 [3 4]]
                     {:co-ords [12.37 53.78]}})

Keywords (names starting with :) are keys pointing to values, in this case other data structures

Data Structure examples

Expressive data structures made code more understandable

(def locations {
     :london {:latitude 34, :longtitude 57}})

(def location {
     :london     {:gps {:co-ords [12.37 53.78]}}
     :new-york   {:gps {:co-ords [12.37 53.78]}}
     :Birmingham {:gps {:co-ords [12.37 53.78]}}})

Small, Composable Components

Clojure was "Microservices" before the idea was coined

Similar to the design principles of Unix

  • do one thing and do it well
  • easily compose things together with functions

Language design

A very small core library

  • with a large set of libraries

Build Automation, logic, asyncronous communication, static type system

Only a handful of building blocks

Clojure primatives

if let loop recur do set! quote var

And a few extra to make Java Interop nice

new . throw try

Stateless approach to design

  • immutability is the default
  • persistent collections
  • Software Transactional Memory (make changes like an atomic database)

In-depth look at Collections

Data Types

  • arbritrary precision integers
  • Doubles 1.234, BigDecials 1.23M
  • Rations 22/7
  • Strings "jr0cket", Characters \a \b \c
  • Symbols fred wilma , keywords :barney :betty (fast keys for maps)
  • Boolean true false , Null nil (nil is false, `is nil` as a condition (eg, if else))
  • Regex patterns #"a*b"

A great way to explain Clojure is to talk about data

Persistent Data Structures

Lists, Vectors, Maps & Sets are all immutable

  • cannot be changed once defined

Modifying persistent data structures

Making a change creates a new data structure

  • contains only the change
  • links back to the original data structure
  • original data structure remains unchanged

Software Transational Memory (STM)

Change data in a controlled way

  • live having an atomic in-memory database

Define Atoms and swap! their values

Efficient Memory use

Sharing Memory

Persistent Data Structures are immutable

Evaluating functions over data structures returns a new result

Updating data structures is simulated by memory sharing

Sharing Memory visualised

A persistent data structure is a binary tree in Clojure

If you try change a persistent data structure, a new one is returned


Lazy Evaluation

Efficiently work with large data structures by only evaluating what is needed

Simplest example is the Ratio type

Tail Recursion

Tail Recursion re-uses memory space efficiently

(defn recursive-function [args]
  (recur (recursive-function args)))

Dynamic development

  • REPL
  • define functions on the fly
  • load & compile code at runtime (load fixes into running production)
  • introspection - not just typing things in, but accessing the Clojure runtime

Notions of phases of compilation are relaxed, you are compiling all the time into bytecode


Macros allow developers to create new features for the language

  • no waiting for the langugage designers

All of Clojure

Special Ops are the Clojure language, everything else is a Macro

fn let loop recur do new . throw try set! quote var def if

Build Tool Macro

Leiningen makes it really easy to define a Clojure project using a Macro

(defproject name version 
  :description ""
  :dependencies [ [library version] [] ])

The Whole JVM world of Libraries

Easy to use Java/JVM libraries from Clojure


Importing libraries


java.lang library is always included

Example: Java Date

A function to return the current date

(defn now [] (java.util.Date.))

Example: Java Math

Define a symbol to represent Pi

(def pi Math/PI)

Example: Joda Time

clj-time is a wrapper around joda-time

(require '[clj-time.core :as time])
(require '[clj-time.format :as time-format])

(time/now) => #<DateTime 2013-03-31T03:23:47.328Z>

(def time-formatter (time-format/formatters :basic-date-time))  ;; ISO 8601 UTC format
(time-format/unparse custom-formatter (date-time 2010 10 3)) => "20101003T000000.000Z"

Wealth of existing Java libraries

  • many wrappers to make them even easier to use
  • nicer to code in Clojure than Java

Amazing Clojure Libraries


Asynchronus coding as a library


Type system as a library

If you must really define your own types

Amazing community

Lets play with Clojure

Lets write some clojure using LightTable

Learning Clojure

(false? (afraid brackets))
  • Learn Clojure on the Internet
  • Read some Clojure books
  • find or start a Clojure / Functional meetup


An increasingly difficult set of changenges to help you understand Clojure


4Clojure - simple example


4Clojure - more complexe example



Blogs, Documentation, etc.

Planet Clojure - blog aggregator - Clojure, Emacs & Git articles - official documentation - community docs & examples

Clojure Cheatsheet - quick syntax & function reference

Thank you


Clojure Development Tools

Leiningen for everything

Leiningen allows you to:

  • Create projects
  • Manage dependencies (uses mvn local cache)
  • Package projects into libraries
  • Generate Maven POM files (if you must)
  • Deploy your libraries on Clojars
  • Run the REPL

Leiningen Requirements

Must have the Java JDK (not just the JRE)

  • this is a requirement for any Clojure development

Leiningen Demo

Time for some live hacking…

Leiningen core commands

  • Create a new project

lein new project-name

  • Check dependencies and download any required

lein deps

  • Run a REPL

lein repl

  • Find out more

lein help

Demo code - project.clj

A basic Leiningen project definition

(defproject whats-my-salary "0.1.0-SNAPSHOT"
  :description "Calculate salary after tax for perminant employees"
  :url ""
  :license {:name "Eclipse Public License"
            :url ""}
  :dependencies [[org.clojure/clojure "1.4.0"]]
  :main whats-my-salary.core )

Demo code - more stuff..

Colourful code

(defn show-me-the-colours [colour]
   ( str "The colour of money is" colour))

Emacs for Clojure

Emacs is a powerful tool for your developer life, its a nice editor too…

  • development environments for lots of languages
  • manage tasks, take effective notes and create presentations

Emacs Live

Creates an amazing environment for Clojure development

  • keeping () under control with ParEdit
  • starting / connecting to a REPL
  • evaluating code in-line (C-x C-e) or all the code (C-c C-k)
  • syntax highlighting & auto-complete
  • gloriously colourful themes

Roll your own Emacs setup

Add the following Emacs packages

clojure-mode clojure-test-mode rainbow-delimiters ac-slime

Look at my basic setup on

Learning Lisp with Emacs

Configuring Emacs is via a Lisp language called ELisp

  • practice your core Clojure skills by tweaking Emacs
  • lots of examples of Lisp code on Github

Light Table

A project to create a great experience for Clojure Development

  • instarepl
  • start / connect to multiple REPL's
  • written in Clojurescript & a few lines of Clojure
  • run browser & graphics in a window
  • also supports Clojurescript, JavaScript & Python
  • still beta, not officially release as yet
  • join light-table-discussion Google group to keep up with changes

Installing Light Table - binaries for Linux (32bit & 64bit), MacOSX & Windows


Built in documentation

Chris Granger's blog - major announcements & a few guides

Java IDE's

Eclipse & Counterclockwise

A great combo if you are used to Eclipse

  • uses Leiningen underneath
  • provides a REPL window
  • usual syntax highlighting and other IDE stuff

Netbeans & Enclojure

Sadly the Enclojure plugin for Netbeans is depreciated

The Enclojure code is available on Github, if you want to kickstart the project.

Intelij & LaClojure

Getting started with La Clojure

Case Studies

Clojure Conj 2014 Lucas Cavalcanti & Edward Wible - how they use Datomic to implement their banking service. 1 You can find the talk on youtube. 2

Thank you

Get Leiningen

Use Emacs, LightTable or your favourite IDE

Have fun in the REPL and love writing Clojure