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
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
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 ??
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 !!
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
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
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
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))) )
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
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
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
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
Hickey'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 "side effects" ā 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.
Throw away your knowledge about OO and try something different
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.
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.
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.
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.
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.
Note: prefix notation
What are the 7 primitive functions?
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 'examples/introduction)
The use function does both require refer, like so ā
(use 'examples.introduction)
o force a library to reload:
(use :reload-all 'examples.introduction)
The :reload-all flag is useful if you are making changes and want to see results without restarting the REPL.
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> (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'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'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!
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.
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.