SlideShare a Scribd company logo
GGeettttiinngg ssttaarrtteedd wwiitthh 
((CClloojjuurree)) 
- or how I learned to stop worrying 
and love the (function)
Its a strange kind of love... 
 Clojure is very different 
 Part of your brain may rebel !! 
 Homo-Iconic 
 List based 
 Immutable state 
 Dynamically typed 
 Tiny syntax 
 Infinitely extensible 
with Macros
What is Clojure 
 Functional programming on the JVM 
 A better Lisp ?
Why get functional ? 
 Clock speeds stopped getting faster around 
2005 
 Cant get around the speed of silicon switches 
 Moores law still in effect 
 More cores added every 18 months 
 Laptops with 128 cores by 2020 ?? 
 Concurrency at the hardware level 
 Not just multi-threading
You may end up working 
here...
Why a better Lisp ? 
 Clojure is easier to understand 
 Nicer libraries 
 Great interoperability with Java 
platform 
 Closer to pure functional 
language 
 Explicitly define mutable state 
 STM – transactional memory
Classic or Re-Imagined 
 Lisp  Clojure
Why create Clojure 
 Concurrency in Java / OO is challenging 
 Mutable state-full paradigm 
 Fast enough persistent data structures made it 
viable 
 Functions as first class 
 Functions part of data structure 
 Functions do not have “side effects” 
 Focus on computation (maths) rather than 
procedural algorithms
Why use Clojure 
 Its a pure functional programming language 
 You can use existing Java code and platform 
 Simple syntax 
 It gets you thinking differently !!! 
 An excuse to learn Emacs properly ??
The downside of Clojure 
( x )
The downside of Clojure (2) 
( ( x ) )
The downside of Clojure (3) 
( ( ( x ) ) )
The downside of Clojure (4) 
( ( ( ( x ) ) ) )
The downside of Clojure (...) 
( ( ( ( ( x ) ) ) ) )
Tool support 
 Emacs 
 clojure-mode, clojure-test, 
paredit-mode 
 Netbeans 
 enclojure 
 IntelliJ 
 La Clojure 
 Eclipse 
 Counterclockwise 
plugin 
 Build tools 
 Leiningen 
 Emacs + Slime 
 Cake 
 Maven
Lets look at Clojure code
Getting started with Clojure
We're not in Kansas any 
more... 
 Java 
package … ; 
class …; 
member variables; 
access retType methodName (param, param) {…} 
 Clojure 
(ns name-space-name) 
(defstruct my-data-struture :label-name) 
(functionName param (fn param)) 
; param's can be functions too !!
Its just a tree...
… a tree structure 
 Functions are data 
 Data structures are functions !!
Download 
 clojure.org 
 Or via buld tool 
 Maven 
 Leiningen 
 Cake 
 Java 
 At least version 5 
 Version 6 better 
performance and 
reporting
All hail the REPL 
 An interactive shell for clojure 
 Using Leiningen (Line – ing – en) 
https://github.com/technomancy/leiningen/ 
lein 
lein repl
Leiningen Clojure project 
lein new 
lein deps 
lein repl 
lein swank 
 Create a new clojure project 
 Download clojure 
 Start the interactive shell 
 Start repl server for emacs
Leiningen project file 
(defproject my-jax-london-project "1.0.0-SNAPSHOT" 
:description "A meaningful description" 
:dependencies [[org.clojure/clojure "1.2.1"] 
[org.clojure/clojure-contrib "1.2.0"]] 
:dev-dependencies [[swank-clojure "1.2.1"] 
[org.clojars.rayne/autodoc "0.8.0- 
SNAPSHOT"]] 
:autodoc { :name "London Clojure dojo", :page-title "Dojo API"} 
;; Only re-fetch deps when they change in project.clj or when :library-path directory is empty. 
:checksum-deps true 
:license {:name "Eclipse Public License - v 1.0"
Loading code into the REPL 
(load-file "temp.clj") 
 Stuff too big to type 
 use an absolute path or a path relative to 
where you launched the REPL 
 Use Emacs or other IDE when you're ready
Simplest possible examples 
(* 2 2) 
(+ 1 2 3) 
( 24 4 3 2) 
( 2 4) 
( 2.0 4) 
(+ (* 4 5) 22) 
(+ 4 (* 3 2) 7) 
(+ 3 (* 2 (- 7 2) 4) (/ 16 4))
Calling Java... ooooo!! 
(javax.swing.JOptionPane/ 
showMessageDialog nil "Hello World" )
Ratio 
 Basic data type 
 Allow delaying computation 
 Avoid loss of precision 
(/ 2 4) 
(/ 2.0 4) 
(/ 1 3) 
(/ 1.0 3) 
(class (/ 1 3)
Simple function example 
(defn hello-world [name] (println(str "Hello " 
name))) 
(hello-world "jr0cket")
What class is that... 
(class (str "Jr0cket")) 
java.lang.String 
(class (defn hello-world [name] (str "Hello cruel 
world"))) 
clojure.lang.Var
str 
(str h e l l o)  Concatenate strings 
together 
 Can represent a 
character using
Booleans / Expressions 
(= 1 1.0) 
(= 1 2) 
(< 1 2) 
 True is a symbol, but 
also 
user=> (class true) 
java.lang.Boolean 
(if 0 (println “True”)) 
(if nil (println “True”)) 
(if “” (println “True”))
More examples 
(last [1 1 2 3 5 8]) 
(defn penultimate [x] 
(last (butlast x)) ) 
(penultimate [1 2 3 4 5]) 
 (doc last) 
 (doc butlast)
And more... 
(nth [1 1 2 3 5 8] 2) 
(count [1 1 2 3 5 8]) 
(reverse [1 1 2 3 5 8]) 
(defn palindrome? [x] 
(= x (reverse x)) ) 
 Proposition – naming 
convention
Even more 
(flatten [[1 1] 2 [3 [5 8]]]) 
(compress "aaaabccaadeeee") 
(encode "aaaabccaadeeee") 
(replicate 10 "a")
Where to find out more... 
http://clojure.org/cheatsheet 
http://clojure.github.com/cloj 
ure/clojure.core-api.html
Your own functions 
 Define your own algorithms 
(defn square [x] (* x x))
Anonymous functions 
 (fn ) (# ) 
(def sqr #(* % %))
Overloading functions 
(defn make 
([ ] ; the make function that takes no arguments 
(struct vector 0 0)) 
([x y] ; ... takes x and y keywords as arguments 
(struct vector x y)) 
)
Pure functions – no side effects 
 Clojure functions are pure 
 they have no side effects 
 Unless you define them as such 
 Pure functions are easy to develop, test, and 
understand 
 Aim for pure functions where possible
Clojure data structures 
 ( Lists ) - Ordered collection of elements 
 (list 1 3 5) '(8 13 21) 
 { map } 
 
 [ Vectors ] - Optimised for random access 
 [:tom :dick :harry] 
 Lists are for code, Vectors for data 
 (nth [:tom :dick :jane :harry ] 2)
List operations 
(first 1 2 3) 
 The head of the list 
(last 7 8 9) 
 The last element of the list 
(rest 1 2 3 4 5) 
 Everything but the head 
(cons :new-list '(1 2 3 4 5)) 
 New list, given head and tail
More data structures... 
(defstruct date :day :month :year) 
(struct date) 
 as we did not specify any parameters, we just 
get nil values 
 things in curly brackets are hash maps - the 
usual Java hashmaps
maps 
 { :a 1 :b 2} 
 user=> { :a 1 :b 2} 
 {:a 1, :b 2} 
 user=> { :a 1 :b } 
 java.lang.ArrayIndexOutOfB 
oundsException: 3 
 user=> { :a 1 :b 2} 
 {:a 1, :b 2} 
 user=> { :a 1 :b 3} ; this 
should make the repl 
complain in clojure 1.2, 
fine in 1.1 
 {:a 1, :b 3} 
 user=> {:a {:a 1}} 
 {:a {:a 1}} 
 user=> {{:a 1} :a} 
 {{:a 1} :a} 
 ; idiom - put :a on the left
Vectors 
 [:neo :morpheus :trinity :smith] 
 [:matrix-characters [:neo :morpheus :trinity 
:smith]] 
 (first [:neo :morpheus :trinity :smith]) 
 (nth [:matrix :babylon5 :firefly :stargate] 2) 
 (concat [:neo] [:trinity]) 
 (def my-vector 
 (vector? x)
Your own data structures 
 Special forms 
(def johnny {:first-name "John", :last-name 
"Stevenson"}) 
(defstruct person :first-name :last-name) 
(defrecord person [String :first-name String 
:last-name] :allow-nulls false)
Memory use 
 Once all references to an immutable structure 
disappears it can be garbage collected. 
 Loops that create intermittent structures are 
garbage collected every turn of the loop. 
;;Memory : 0 
(let [a (range 50000)]) ;; Memory: "big" while 
the let is "executing" 
;;Memory : 0 -- no reference to a anymore !
macros 
 Define extensions to the language 
 Clojure only has 7 primitive functions 
 Everything else in the language is created with 
macros 
 Allows the language to be extended easily 
without changes to the compiler
Special forms 
 Recognized by the Clojure compiler and not 
implemented in Clojure source code. 
 A relatively small number of special forms 
 New ones cannot be implemented 
 catch, def, do, dot ('.'), finally, fn, if, let, loop, 
monitor-enter, monitor-exit, new, quote, 
recur, set!, throw, try and var
if 
user=> (doc if) 
------------------------- 
if 
Special Form 
Please see http://clojure.org/special_forms#if 
nil
Sequences 
 Sequences are logical views of collections 
 Logical lists 
 Java collections, Clojure-specific collections, 
strings, streams, directory structures and XML 
trees. 
 New Clojure collections created efficiently 
 Creates a sort of branch (delta) in the data 
structure tree
Working with Sequences 
 first 
 rest 
 cons
Software Transactional 
Memory 
 Works like transactional databases 
 Provides safe, concurrent access to memory 
 Agents allow encapsulated access to mutable 
resources
Sharing mutable data 
 Use mutable references to immutable data 
 Reference Types 
 synchronous access to multiple pieces of 
shared data ("coordinated") by using STM 
 Atoms 
 synchronous access to a single piece of shared 
data. 
 Agents 
 asynchronous access to a single piece of 
shared data
Name-spaces 
 Define a namespace 
(ns name-space-name) 
 Include namespace code 
(use 'names-space-name) 
 Like a package statement in Java
Clojure Libraries 
(use 'clojure.contrib.str-utils) 
' 
 Dont treat the next thing as a function 
 Open source libraries - http://clojars.org/
Recursive functions 
 Functions that call 
themselves 
 Fractal coding 
 Tail recursion 
 Avoids blowing the 
heap 
 A trick as the JVM 
does not support 
tail recursion 
directly :-(
Tail recursion 
(defn factorial [x] 
(if (= x 0) 
1 
(* x (factorial (- x 1)) 
))) 
 Dont blow your stack 
!!
TDD with Clojure is nice 
 Clojure test 
(deftest test-name 
(is (= value (function params))) )
Simple test 
(ns simple-test 
(:use clojure.test) 
(:use simple)) 
(deftest simple-test 
(is (= (hello) "Hello world!")) 
(is (= (hello "test") "Hello test!")))
Working with Java 
 Java Classes 
 fullstop after class name 
 (JFrame. ) 
 (Math/cos 3) ; static method call 
 Java methods 
 fullstop before method name 
 (.getContentPane frame) ;;method name first 
 (. frame getContentPane) ;;object first
Importing 
(ns drawing-demo 
(:import [javax.swing JPanel JFrame] 
[java.awt Dimension]))
Working with Java (2) 
 Clojure gives you clean, simple, direct access 
to Java 
 call any Java API directly 
 (System/getProperties) 
 -> {java.runtime.name=Java(TM) SE Runtime 
Environment
Calling Clojure from Java 
 Export the clojure to a .jar 
 Add the jar to the classpath 
 Import the library in your code 
 Call it like any other method
Errors are inevitable 
 In the REPL 
(printStackTrace *e) 
 *e holds the last exception raised 
 Clojure exceptions are Java exceptions
Managing State in Immutable 
world 
 Mutable data structures to share between 
threads (Software Transactional Memory) 
 refs, vars, atoms, agents 
 No locks required for thread safe code, no 
deadlocks or race conditions 
 Atomically apply changes
Mutable functions 
 Swap! 
 
 Name functions that have side effects with an 
exclamation mark 
 Naming convention
Deployment 
 lein jar 
 lein uberjar
Documentation 
(doc function-name) 
(javadoc class-name) 
(defn function-name 
“A meaningful 
description of the 
function” 
params ) 
 Show fn description 
 Show javadoc in 
browser 
 Write documentation 
for your own 
functions
Example documentation 
(doc str) 
Use doc to print the documentation for str: 
user=> (doc str) 
------------------------- 
clojure.core/str 
([] [x] [x & ys]) 
With no args, returns the empty string. With one 
arg x, returns x.toString(). (str nil) returns 
the empty string. With more than one arg, 
returns the concatenation of the str values 
of the args. 
 Fully qualified 
namespace 
 Arguments 
 Details
find-doc 
(find-doc “reduce”) 
user=> (find-doc "reduce" ) 
------------------------- 
clojure/areduce 
([a idx ret init expr]) 
Macro 
... details ... 
------------------------- 
clojure/reduce 
([f coll] [f val coll]) 
... details ... 
 Search for functions 
you dont know 
 Keyword parameter
Autodoc 
 Generate a website for your API's 
 http://tomfaulhaber.github.com/auto 
doc/ 
 Add dependency to your build file 
 http://clojars.org/org.clojars.rayne/autodoc 
 lein deps 
 lein autodoc
Where next 
 Coding dojo – London / start your own 
 www.londonjavacommunity.co.uk 
 Books – Programming Clojure (Pragmatic) 
 Website – clojure.org dev.clojure.org 
 Full Disclojure 
vimeo.com/channels/fulldisclojure 
 clojure.jr0cket.co.uk 
 99 problems in clojure
Credits 
No parentheses 
were harmed in the 
making of this 
presentation....
TThhaannkk yyoouu 
 HHaavvee ffuunn 
lleeaarrnniinngg !!!! 
JJoohhnn@@jjrr00cckkeett..ccoomm 
@@jjrr00cckkeett 
jjoohhnn..jjrr00cckkeett..ccoo..uukk 
cclloojjuurree..jjrr00cckkeett..ccoo..uukk

More Related Content

What's hot (20)

PDF
Oscon Java Testing on the Fast Lane
Andres Almiray
 
PDF
Java7 New Features and Code Examples
Naresh Chintalcheru
 
PDF
From Java to Parellel Clojure - Clojure South 2019
Leonardo Borges
 
PDF
JavaOne 2013 - Clojure for Java Developers
Jan Kronquist
 
PDF
Exploring Clojurescript
Luke Donnet
 
DOCX
Advance Java Programs skeleton
Iram Ramrajkar
 
PPTX
06 Java Language And OOP Part VI
Hari Christian
 
PPTX
TclOO: Past Present Future
Donal Fellows
 
PDF
Scala coated JVM
Stuart Roebuck
 
PPTX
Adventures in TclOO
Donal Fellows
 
PDF
Excuse me, sir, do you have a moment to talk about tests in Kotlin
leonsabr
 
PDF
Spock: A Highly Logical Way To Test
Howard Lewis Ship
 
PPTX
Kotlin is charming; The reasons Java engineers should start Kotlin.
JustSystems Corporation
 
DOC
Ad java prac sol set
Iram Ramrajkar
 
PDF
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
PDF
Introduction to clojure
Abbas Raza
 
KEY
Clojure: a LISP for the JVM
Knowledge Engineering and Machine Learning Group
 
PDF
Java 7 New Features
Jussi Pohjolainen
 
PDF
Blocks & GCD
rsebbe
 
PDF
Spock: Test Well and Prosper
Ken Kousen
 
Oscon Java Testing on the Fast Lane
Andres Almiray
 
Java7 New Features and Code Examples
Naresh Chintalcheru
 
From Java to Parellel Clojure - Clojure South 2019
Leonardo Borges
 
JavaOne 2013 - Clojure for Java Developers
Jan Kronquist
 
Exploring Clojurescript
Luke Donnet
 
Advance Java Programs skeleton
Iram Ramrajkar
 
06 Java Language And OOP Part VI
Hari Christian
 
TclOO: Past Present Future
Donal Fellows
 
Scala coated JVM
Stuart Roebuck
 
Adventures in TclOO
Donal Fellows
 
Excuse me, sir, do you have a moment to talk about tests in Kotlin
leonsabr
 
Spock: A Highly Logical Way To Test
Howard Lewis Ship
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
JustSystems Corporation
 
Ad java prac sol set
Iram Ramrajkar
 
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
Introduction to clojure
Abbas Raza
 
Java 7 New Features
Jussi Pohjolainen
 
Blocks & GCD
rsebbe
 
Spock: Test Well and Prosper
Ken Kousen
 

Viewers also liked (20)

PDF
Clojure: an overview
Larry Diehl
 
PDF
Clojure: The Art of Abstraction
Alex Miller
 
PDF
DSL in Clojure
Misha Kozik
 
KEY
Functional programming in clojure
Juan-Manuel Gimeno
 
PDF
Clojure, Web and Luminus
Edward Tsech
 
PDF
Yet another startup built on Clojure(Script)
Paul Lam
 
PDF
Intro to Java 8 Closures (Dainius Mezanskas)
Kaunas Java User Group
 
KEY
Clojure at BackType
nathanmarz
 
PDF
Writing DSL in Clojure
Misha Kozik
 
PDF
ETL in Clojure
Dmitriy Morozov
 
PDF
Functional Reactive Programming in Clojurescript
Leonardo Borges
 
PDF
EPUB3で変わる電子書籍の表現力
Youji Sakai
 
PDF
JS Lab`16. Роман Лютиков: "ClojureScript, что ты такое?"
GeeksLab Odessa
 
PDF
HTML5와 전자책, 융합 서비스로 발전 현황
Open Cyber University of Korea
 
PPTX
DITA, HTML5, and EPUB3 (Content Agility, June 2013)
Contrext Solutions
 
PDF
EPUB3 Now! at IDPF 2013 Digital Book
liz_castro
 
KEY
Winning the Erlang Edit•Build•Test Cycle
Rusty Klophaus
 
PDF
Messaging With Erlang And Jabber
l xf
 
PDF
Clojure class
Aysylu Greenberg
 
PDF
20 reasons why we don't need architects (@pavlobaron)
Pavlo Baron
 
Clojure: an overview
Larry Diehl
 
Clojure: The Art of Abstraction
Alex Miller
 
DSL in Clojure
Misha Kozik
 
Functional programming in clojure
Juan-Manuel Gimeno
 
Clojure, Web and Luminus
Edward Tsech
 
Yet another startup built on Clojure(Script)
Paul Lam
 
Intro to Java 8 Closures (Dainius Mezanskas)
Kaunas Java User Group
 
Clojure at BackType
nathanmarz
 
Writing DSL in Clojure
Misha Kozik
 
ETL in Clojure
Dmitriy Morozov
 
Functional Reactive Programming in Clojurescript
Leonardo Borges
 
EPUB3で変わる電子書籍の表現力
Youji Sakai
 
JS Lab`16. Роман Лютиков: "ClojureScript, что ты такое?"
GeeksLab Odessa
 
HTML5와 전자책, 융합 서비스로 발전 현황
Open Cyber University of Korea
 
DITA, HTML5, and EPUB3 (Content Agility, June 2013)
Contrext Solutions
 
EPUB3 Now! at IDPF 2013 Digital Book
liz_castro
 
Winning the Erlang Edit•Build•Test Cycle
Rusty Klophaus
 
Messaging With Erlang And Jabber
l xf
 
Clojure class
Aysylu Greenberg
 
20 reasons why we don't need architects (@pavlobaron)
Pavlo Baron
 
Ad

Similar to Getting started with Clojure (20)

PPTX
Clojure 7-Languages
Pierre de Lacaze
 
ODP
Clojure presentation
Tikal Knowledge
 
PDF
Clojure - LISP on the JVM
Tikal Knowledge
 
ODP
Clojure made simple - Lightning talk
John Stevenson
 
ODP
Clojure basics
Knoldus Inc.
 
PDF
From Java To Clojure (English version)
Kent Ohashi
 
KEY
(map Clojure everyday-tasks)
Jacek Laskowski
 
PDF
Introduction to Clojure
Renzo Borgatti
 
ODP
Clojure made really really simple
John Stevenson
 
PDF
The Ideas of Clojure - Things I learn from Clojure
Hsuan Fu Lien
 
PPTX
Clojure through the eyes of a Java Nut | [Mixed Nuts] at Pramati Technologies
Pramati Technologies
 
PDF
Clojure
Rohit Vaidya
 
PPTX
Clojure Fundamentals Course For Beginners
Paddy Lock
 
PDF
'Getting' Clojure - '(parentheses are just hugs for your code)
Gary Trakhman
 
PDF
Clojure 1.1 And Beyond
Mike Fogus
 
PDF
Clojure and The Robot Apocalypse
elliando dias
 
PDF
A Taste of Clojure
David Leung
 
PDF
Introductory Clojure Presentation
Jay Victoria
 
PDF
Clojure - A practical LISP for the JVM
Matthias Nüßler
 
PDF
Functional web with clojure
John Stevenson
 
Clojure 7-Languages
Pierre de Lacaze
 
Clojure presentation
Tikal Knowledge
 
Clojure - LISP on the JVM
Tikal Knowledge
 
Clojure made simple - Lightning talk
John Stevenson
 
Clojure basics
Knoldus Inc.
 
From Java To Clojure (English version)
Kent Ohashi
 
(map Clojure everyday-tasks)
Jacek Laskowski
 
Introduction to Clojure
Renzo Borgatti
 
Clojure made really really simple
John Stevenson
 
The Ideas of Clojure - Things I learn from Clojure
Hsuan Fu Lien
 
Clojure through the eyes of a Java Nut | [Mixed Nuts] at Pramati Technologies
Pramati Technologies
 
Clojure
Rohit Vaidya
 
Clojure Fundamentals Course For Beginners
Paddy Lock
 
'Getting' Clojure - '(parentheses are just hugs for your code)
Gary Trakhman
 
Clojure 1.1 And Beyond
Mike Fogus
 
Clojure and The Robot Apocalypse
elliando dias
 
A Taste of Clojure
David Leung
 
Introductory Clojure Presentation
Jay Victoria
 
Clojure - A practical LISP for the JVM
Matthias Nüßler
 
Functional web with clojure
John Stevenson
 
Ad

More from John Stevenson (20)

PDF
ClojureX Conference 2017 - 10 amazing years of Clojure
John Stevenson
 
PDF
Confessions of a developer community builder
John Stevenson
 
PDF
Progscon 2017: Taming the wild fronteer - Adventures in Clojurescript
John Stevenson
 
PDF
Introduction to Functional Reactive Web with Clojurescript
John Stevenson
 
PDF
Thinking Functionally with Clojure
John Stevenson
 
PDF
Communication improbable
John Stevenson
 
PDF
Getting into public speaking at conferences
John Stevenson
 
PDF
Get into Functional Programming with Clojure
John Stevenson
 
PDF
Guiding people into Clojure
John Stevenson
 
PDF
Git and github - Verson Control for the Modern Developer
John Stevenson
 
PDF
Get Functional Programming with Clojure
John Stevenson
 
PDF
So you want to run a developer event, are you crazy?
John Stevenson
 
PPTX
Trailhead live - Overview of Salesforce App Cloud
John Stevenson
 
PPTX
Introducing the Salesforce platform
John Stevenson
 
PPT
Dreamforce14 Metadata Management with Git Version Control
John Stevenson
 
PPT
Salesforce Summer of Hacks London - Introduction
John Stevenson
 
PPTX
Heroku Introduction: Scaling customer facing apps & services
John Stevenson
 
PPT
Developers guide to the Salesforce1 Platform
John Stevenson
 
PPTX
Developer week EMEA - Salesforce1 Mobile App overview
John Stevenson
 
PPT
Dreamforce 13 developer session: Git for Force.com developers
John Stevenson
 
ClojureX Conference 2017 - 10 amazing years of Clojure
John Stevenson
 
Confessions of a developer community builder
John Stevenson
 
Progscon 2017: Taming the wild fronteer - Adventures in Clojurescript
John Stevenson
 
Introduction to Functional Reactive Web with Clojurescript
John Stevenson
 
Thinking Functionally with Clojure
John Stevenson
 
Communication improbable
John Stevenson
 
Getting into public speaking at conferences
John Stevenson
 
Get into Functional Programming with Clojure
John Stevenson
 
Guiding people into Clojure
John Stevenson
 
Git and github - Verson Control for the Modern Developer
John Stevenson
 
Get Functional Programming with Clojure
John Stevenson
 
So you want to run a developer event, are you crazy?
John Stevenson
 
Trailhead live - Overview of Salesforce App Cloud
John Stevenson
 
Introducing the Salesforce platform
John Stevenson
 
Dreamforce14 Metadata Management with Git Version Control
John Stevenson
 
Salesforce Summer of Hacks London - Introduction
John Stevenson
 
Heroku Introduction: Scaling customer facing apps & services
John Stevenson
 
Developers guide to the Salesforce1 Platform
John Stevenson
 
Developer week EMEA - Salesforce1 Mobile App overview
John Stevenson
 
Dreamforce 13 developer session: Git for Force.com developers
John Stevenson
 

Recently uploaded (20)

PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 

Getting started with Clojure

  • 1. GGeettttiinngg ssttaarrtteedd wwiitthh ((CClloojjuurree)) - or how I learned to stop worrying and love the (function)
  • 2. Its a strange kind of love...  Clojure is very different  Part of your brain may rebel !!  Homo-Iconic  List based  Immutable state  Dynamically typed  Tiny syntax  Infinitely extensible with Macros
  • 3. What is Clojure  Functional programming on the JVM  A better Lisp ?
  • 4. Why get functional ?  Clock speeds stopped getting faster around 2005  Cant get around the speed of silicon switches  Moores law still in effect  More cores added every 18 months  Laptops with 128 cores by 2020 ??  Concurrency at the hardware level  Not just multi-threading
  • 5. You may end up working here...
  • 6. Why a better Lisp ?  Clojure is easier to understand  Nicer libraries  Great interoperability with Java platform  Closer to pure functional language  Explicitly define mutable state  STM – transactional memory
  • 7. Classic or Re-Imagined  Lisp  Clojure
  • 8. Why create Clojure  Concurrency in Java / OO is challenging  Mutable state-full paradigm  Fast enough persistent data structures made it viable  Functions as first class  Functions part of data structure  Functions do not have “side effects”  Focus on computation (maths) rather than procedural algorithms
  • 9. Why use Clojure  Its a pure functional programming language  You can use existing Java code and platform  Simple syntax  It gets you thinking differently !!!  An excuse to learn Emacs properly ??
  • 10. The downside of Clojure ( x )
  • 11. The downside of Clojure (2) ( ( x ) )
  • 12. The downside of Clojure (3) ( ( ( x ) ) )
  • 13. The downside of Clojure (4) ( ( ( ( x ) ) ) )
  • 14. The downside of Clojure (...) ( ( ( ( ( x ) ) ) ) )
  • 15. Tool support  Emacs  clojure-mode, clojure-test, paredit-mode  Netbeans  enclojure  IntelliJ  La Clojure  Eclipse  Counterclockwise plugin  Build tools  Leiningen  Emacs + Slime  Cake  Maven
  • 16. Lets look at Clojure code
  • 18. We're not in Kansas any more...  Java package … ; class …; member variables; access retType methodName (param, param) {…}  Clojure (ns name-space-name) (defstruct my-data-struture :label-name) (functionName param (fn param)) ; param's can be functions too !!
  • 19. Its just a tree...
  • 20. … a tree structure  Functions are data  Data structures are functions !!
  • 21. Download  clojure.org  Or via buld tool  Maven  Leiningen  Cake  Java  At least version 5  Version 6 better performance and reporting
  • 22. All hail the REPL  An interactive shell for clojure  Using Leiningen (Line – ing – en) https://github.com/technomancy/leiningen/ lein lein repl
  • 23. Leiningen Clojure project lein new lein deps lein repl lein swank  Create a new clojure project  Download clojure  Start the interactive shell  Start repl server for emacs
  • 24. Leiningen project file (defproject my-jax-london-project "1.0.0-SNAPSHOT" :description "A meaningful description" :dependencies [[org.clojure/clojure "1.2.1"] [org.clojure/clojure-contrib "1.2.0"]] :dev-dependencies [[swank-clojure "1.2.1"] [org.clojars.rayne/autodoc "0.8.0- SNAPSHOT"]] :autodoc { :name "London Clojure dojo", :page-title "Dojo API"} ;; Only re-fetch deps when they change in project.clj or when :library-path directory is empty. :checksum-deps true :license {:name "Eclipse Public License - v 1.0"
  • 25. Loading code into the REPL (load-file "temp.clj")  Stuff too big to type  use an absolute path or a path relative to where you launched the REPL  Use Emacs or other IDE when you're ready
  • 26. Simplest possible examples (* 2 2) (+ 1 2 3) ( 24 4 3 2) ( 2 4) ( 2.0 4) (+ (* 4 5) 22) (+ 4 (* 3 2) 7) (+ 3 (* 2 (- 7 2) 4) (/ 16 4))
  • 27. Calling Java... ooooo!! (javax.swing.JOptionPane/ showMessageDialog nil "Hello World" )
  • 28. Ratio  Basic data type  Allow delaying computation  Avoid loss of precision (/ 2 4) (/ 2.0 4) (/ 1 3) (/ 1.0 3) (class (/ 1 3)
  • 29. Simple function example (defn hello-world [name] (println(str "Hello " name))) (hello-world "jr0cket")
  • 30. What class is that... (class (str "Jr0cket")) java.lang.String (class (defn hello-world [name] (str "Hello cruel world"))) clojure.lang.Var
  • 31. str (str h e l l o)  Concatenate strings together  Can represent a character using
  • 32. Booleans / Expressions (= 1 1.0) (= 1 2) (< 1 2)  True is a symbol, but also user=> (class true) java.lang.Boolean (if 0 (println “True”)) (if nil (println “True”)) (if “” (println “True”))
  • 33. More examples (last [1 1 2 3 5 8]) (defn penultimate [x] (last (butlast x)) ) (penultimate [1 2 3 4 5])  (doc last)  (doc butlast)
  • 34. And more... (nth [1 1 2 3 5 8] 2) (count [1 1 2 3 5 8]) (reverse [1 1 2 3 5 8]) (defn palindrome? [x] (= x (reverse x)) )  Proposition – naming convention
  • 35. Even more (flatten [[1 1] 2 [3 [5 8]]]) (compress "aaaabccaadeeee") (encode "aaaabccaadeeee") (replicate 10 "a")
  • 36. Where to find out more... http://clojure.org/cheatsheet http://clojure.github.com/cloj ure/clojure.core-api.html
  • 37. Your own functions  Define your own algorithms (defn square [x] (* x x))
  • 38. Anonymous functions  (fn ) (# ) (def sqr #(* % %))
  • 39. Overloading functions (defn make ([ ] ; the make function that takes no arguments (struct vector 0 0)) ([x y] ; ... takes x and y keywords as arguments (struct vector x y)) )
  • 40. Pure functions – no side effects  Clojure functions are pure  they have no side effects  Unless you define them as such  Pure functions are easy to develop, test, and understand  Aim for pure functions where possible
  • 41. Clojure data structures  ( Lists ) - Ordered collection of elements  (list 1 3 5) '(8 13 21)  { map }   [ Vectors ] - Optimised for random access  [:tom :dick :harry]  Lists are for code, Vectors for data  (nth [:tom :dick :jane :harry ] 2)
  • 42. List operations (first 1 2 3)  The head of the list (last 7 8 9)  The last element of the list (rest 1 2 3 4 5)  Everything but the head (cons :new-list '(1 2 3 4 5))  New list, given head and tail
  • 43. More data structures... (defstruct date :day :month :year) (struct date)  as we did not specify any parameters, we just get nil values  things in curly brackets are hash maps - the usual Java hashmaps
  • 44. maps  { :a 1 :b 2}  user=> { :a 1 :b 2}  {:a 1, :b 2}  user=> { :a 1 :b }  java.lang.ArrayIndexOutOfB oundsException: 3  user=> { :a 1 :b 2}  {:a 1, :b 2}  user=> { :a 1 :b 3} ; this should make the repl complain in clojure 1.2, fine in 1.1  {:a 1, :b 3}  user=> {:a {:a 1}}  {:a {:a 1}}  user=> {{:a 1} :a}  {{:a 1} :a}  ; idiom - put :a on the left
  • 45. Vectors  [:neo :morpheus :trinity :smith]  [:matrix-characters [:neo :morpheus :trinity :smith]]  (first [:neo :morpheus :trinity :smith])  (nth [:matrix :babylon5 :firefly :stargate] 2)  (concat [:neo] [:trinity])  (def my-vector  (vector? x)
  • 46. Your own data structures  Special forms (def johnny {:first-name "John", :last-name "Stevenson"}) (defstruct person :first-name :last-name) (defrecord person [String :first-name String :last-name] :allow-nulls false)
  • 47. Memory use  Once all references to an immutable structure disappears it can be garbage collected.  Loops that create intermittent structures are garbage collected every turn of the loop. ;;Memory : 0 (let [a (range 50000)]) ;; Memory: "big" while the let is "executing" ;;Memory : 0 -- no reference to a anymore !
  • 48. macros  Define extensions to the language  Clojure only has 7 primitive functions  Everything else in the language is created with macros  Allows the language to be extended easily without changes to the compiler
  • 49. Special forms  Recognized by the Clojure compiler and not implemented in Clojure source code.  A relatively small number of special forms  New ones cannot be implemented  catch, def, do, dot ('.'), finally, fn, if, let, loop, monitor-enter, monitor-exit, new, quote, recur, set!, throw, try and var
  • 50. if user=> (doc if) ------------------------- if Special Form Please see http://clojure.org/special_forms#if nil
  • 51. Sequences  Sequences are logical views of collections  Logical lists  Java collections, Clojure-specific collections, strings, streams, directory structures and XML trees.  New Clojure collections created efficiently  Creates a sort of branch (delta) in the data structure tree
  • 52. Working with Sequences  first  rest  cons
  • 53. Software Transactional Memory  Works like transactional databases  Provides safe, concurrent access to memory  Agents allow encapsulated access to mutable resources
  • 54. Sharing mutable data  Use mutable references to immutable data  Reference Types  synchronous access to multiple pieces of shared data ("coordinated") by using STM  Atoms  synchronous access to a single piece of shared data.  Agents  asynchronous access to a single piece of shared data
  • 55. Name-spaces  Define a namespace (ns name-space-name)  Include namespace code (use 'names-space-name)  Like a package statement in Java
  • 56. Clojure Libraries (use 'clojure.contrib.str-utils) '  Dont treat the next thing as a function  Open source libraries - http://clojars.org/
  • 57. Recursive functions  Functions that call themselves  Fractal coding  Tail recursion  Avoids blowing the heap  A trick as the JVM does not support tail recursion directly :-(
  • 58. Tail recursion (defn factorial [x] (if (= x 0) 1 (* x (factorial (- x 1)) )))  Dont blow your stack !!
  • 59. TDD with Clojure is nice  Clojure test (deftest test-name (is (= value (function params))) )
  • 60. Simple test (ns simple-test (:use clojure.test) (:use simple)) (deftest simple-test (is (= (hello) "Hello world!")) (is (= (hello "test") "Hello test!")))
  • 61. Working with Java  Java Classes  fullstop after class name  (JFrame. )  (Math/cos 3) ; static method call  Java methods  fullstop before method name  (.getContentPane frame) ;;method name first  (. frame getContentPane) ;;object first
  • 62. Importing (ns drawing-demo (:import [javax.swing JPanel JFrame] [java.awt Dimension]))
  • 63. Working with Java (2)  Clojure gives you clean, simple, direct access to Java  call any Java API directly  (System/getProperties)  -> {java.runtime.name=Java(TM) SE Runtime Environment
  • 64. Calling Clojure from Java  Export the clojure to a .jar  Add the jar to the classpath  Import the library in your code  Call it like any other method
  • 65. Errors are inevitable  In the REPL (printStackTrace *e)  *e holds the last exception raised  Clojure exceptions are Java exceptions
  • 66. Managing State in Immutable world  Mutable data structures to share between threads (Software Transactional Memory)  refs, vars, atoms, agents  No locks required for thread safe code, no deadlocks or race conditions  Atomically apply changes
  • 67. Mutable functions  Swap!   Name functions that have side effects with an exclamation mark  Naming convention
  • 68. Deployment  lein jar  lein uberjar
  • 69. Documentation (doc function-name) (javadoc class-name) (defn function-name “A meaningful description of the function” params )  Show fn description  Show javadoc in browser  Write documentation for your own functions
  • 70. Example documentation (doc str) Use doc to print the documentation for str: user=> (doc str) ------------------------- clojure.core/str ([] [x] [x & ys]) With no args, returns the empty string. With one arg x, returns x.toString(). (str nil) returns the empty string. With more than one arg, returns the concatenation of the str values of the args.  Fully qualified namespace  Arguments  Details
  • 71. find-doc (find-doc “reduce”) user=> (find-doc "reduce" ) ------------------------- clojure/areduce ([a idx ret init expr]) Macro ... details ... ------------------------- clojure/reduce ([f coll] [f val coll]) ... details ...  Search for functions you dont know  Keyword parameter
  • 72. Autodoc  Generate a website for your API's  http://tomfaulhaber.github.com/auto doc/  Add dependency to your build file  http://clojars.org/org.clojars.rayne/autodoc  lein deps  lein autodoc
  • 73. Where next  Coding dojo – London / start your own  www.londonjavacommunity.co.uk  Books – Programming Clojure (Pragmatic)  Website – clojure.org dev.clojure.org  Full Disclojure vimeo.com/channels/fulldisclojure  clojure.jr0cket.co.uk  99 problems in clojure
  • 74. Credits No parentheses were harmed in the making of this presentation....
  • 75. TThhaannkk yyoouu  HHaavvee ffuunn lleeaarrnniinngg !!!! JJoohhnn@@jjrr00cckkeett..ccoomm @@jjrr00cckkeett jjoohhnn..jjrr00cckkeett..ccoo..uukk cclloojjuurree..jjrr00cckkeett..ccoo..uukk

Editor's Notes

  • #7: Clojure has a programmatic macro system which allows the compiler to be extended by user code You can add your own language features with macros. Clojure itself is built out of macros such as defstruct: (defstruct person :first-name :last-name) If you need different semantics, write your own macro. If you want a variant of structs with strong typing and configurable null-checking for all fields, you can create your own defrecord macro, to be used like this: (defrecord person [String :first-name String :last-name] :allow-nulls false) This ability to reprogram the language from within the language is the unique advantage of Lisp. You will see facets of this idea described in various ways: Lisp is homoiconic - Lisp code is just Lisp data. This makes it easy for programs to write other programs. The whole language is there, all the time. Paul Graham’s essay “Revenge of the Nerds” explains why this is so powerful. http://www.paulgraham.com/icad.html Lisp syntax also eliminates rules for operator precedence and associativity, with fully parenthesized expressions, there is no possible ambiguity
  • #9: Hickey&amp;apos;s primary interest was concurrency — he wanted the ability to write multi-threaded applications, but increasingly found the mutable, stateful paradigm of object oriented programming to be part of the problem The idea of a functional Lisp integrated with a commercially accepted host platform just seemed like chocolate and peanut butter. Coming up with persistent data structures that were fast enough was the tipping point for my considering it viable. functions as first-class objects, meaning that functions can be placed into data structures, passed as arguments to other functions, evaluated in comparisons, even returned as the return value of another function. Moreover, functions do not have &amp;quot;side effects&amp;quot; — the ability to modify program state or data. This paradigm focuses on computation in the mathematical sense, rather than procedural algorithms, and is a completely different approach to programming. Clojure does provide persistent data structures For application developers, the most significant distinction is that Clojure defaults to making all data structures immutable developers must use one of four special mutable structures that are explicitly designed to be shared between threads: refs, vars, atoms, and agents. Clojure uses software transactional memory (STM) to coordinate changing these mutable structures while keeping them in a consistent state, much like a transactional database. This model makes it considerably simpler to write thread-safe code than it is in object oriented languages. No locks are required, therefore there are no deadlocks or race conditions.
  • #10: Throw away your knowledge about OO and try something different
  • #11: The downside of Lisp’s simple, regular syntax, at least for beginners, is Lisp’s fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.
  • #12: The downside of Lisp’s simple, regular syntax, at least for beginners, is Lisp’s fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.
  • #13: The downside of Lisp’s simple, regular syntax, at least for beginners, is Lisp’s fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.
  • #14: The downside of Lisp’s simple, regular syntax, at least for beginners, is Lisp’s fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.
  • #15: The downside of Lisp’s simple, regular syntax, at least for beginners, is Lisp’s fixation on parentheses and on lists as the core data type. Clojure offers an interesting combination of features that makes Lisp more approachable for non-Lispers.
  • #27: Note: prefix notation
  • #50: What are the 7 primitive functions?
  • #57: When you require a library named clojure.contrib.str-utils, Clojure looks for a file named clojure/contrib/str-utils.clj on the CLASSPATH To avoid having to use the namespace for your library, you have to use refer, like so - (refer &amp;apos;examples/introduction) The use function does both require refer, like so – (use &amp;apos;examples.introduction) o force a library to reload: (use :reload-all &amp;apos;examples.introduction) The :reload-all flag is useful if you are making changes and want to see results without restarting the REPL.
  • #60: This is barfing because the evaluator has to keep around state for each call due to the expression (* x (factorial (- x 1))) . We need to make this function tail recursive. recur can be thought of as the Clojure operator for looping. Think of it like a function call for the nearest enclosing let or function definition supplied with new variables. Naively we can switch over to using this by doing: user&amp;gt; (defn factorial2 [x] (if (= x 0) 1 (* x (recur (- x 1))))) But this is a compile-time error (which in itself is pretty neat!). java.lang.UnsupportedOperationException: Can only recur from tail position (NO_SOURCE_FILE:4) An accumulator parameter is an extra parameter to a function that&amp;apos;s used to gather intermediate parts of the calculation. If we do this, we can make sure that the recur call is in the tail position. Using an anonymous function we get: (defn factorial3 [x] ((fn [x y] (if (= x 0) y (recur (- x 1) (* x y)))) x 1)) Now when recur is used, it doesn&amp;apos;t need to keep any of the previous stack frame around. This means we can finally calculate factorial 1000000, which begins with 282 and ends with lots of zeros!
  • #73: Use doc to print the documentation for str: user=&amp;gt; (doc str) ------------------------- clojure.core/str ([] [x] [x &amp; ys]) With no args, returns the empty string. With one arg x, returns x.toString(). (str nil) returns the empty string. With more than one arg, returns the concatenation of the str values of the args. The first line of doc’s output contains the fully qualified name of the function. The next line contains the possible argument lists, generated directly from the code. (Some common argument names and their uses are explained in the sidebar on the following page.) Finally, the remaining lines contain the function’s doc-string, if the function definition included one.