Thanks to visit codestin.com
Credit goes to www.slideshare.net

Thinking Functionally with
Clojure
by John Stevenson
@jr0cket
www.practical.li
Why Functional Programming
it's not just because it's really fun...
Complex Systems
… are simply not
easy to understand
@jr0cket
Josh Smith - Tweet
Original Gif
The Complexity Iceberg
- @krisajenkins
● complexity is very
dangerous when hidden
● You can't know what a
function does for certain if it
has side effects
Side Effects
Side Causes term coined by
@krisajenkins
Pure Functions
The results of the function are purely determined by its initial output and its own code
- no external influence, a function only uses local values
- referential transparency (the function can be replaced by its value)
Impure Functions - side causes
The results of the function are purely determined by its initial output and its own code
- behaviour externally influenced and non-deterministic
Eliminating Side Effects
Functional programming is about eliminating side effects where you can,
controlling them where you can't - @krisajenkins
The features in Functional Programming come from a
desire to reduce side effects
Clojure
General purpose language hosted on JVM, JavaScript & CLR
Clojure / ClojureScript
A hosted language with simple interoperability with the host language
- (java.Util.Date.)
- (js/alert “Client side apps are easier in Clojure”)
Clojure - basic syntax for this talk
( ) ;; an empty list. The first element of a list is evaluated as a function call
(function-name data) ;; call a function with the data as its argument
(def name “data-or-value”) ;; assign (bind) a name to a data or legal value
:keyword-name ;; a keyword is a name that points to itself
;; Thread-first macro - chain function calls, passing the result of each call as the first
argument to the next function. The ,,, indicates where the resulting argument goes.
(-> (function-a “data”)
(function-b ,,,) ;; In Clojure commas , are whitespace
(function-c ,,, “data”))
Persistent data structures
Built-in Immutability leading to deterministic code
List, Vector, Map & Set
Clojure’s built-in data structures are all immutable
- returning a new data structure when a function is applied
(list 1 2 3 4 5) ‘(“fish” “chips” 42)
(vec ‘(1 2 3 4)) [1 2 3 4]
{:key “value”} {:name “John” :skill “conferencing”}
(set ‘(1 2 3 4 4)) #{1 2 3 4}
Persistent Data Structures - shared memory
Each function creates a new vector
Memory space for values is shared
between each vector
Persistent Data Structures -
shared memory
By sharing memory you
can apply functions
over and over again
effectively
Values persist until
they are no longer
referenced
Concurrency is Easier
Concurrency is much easier to write and reason about because of
- Pure functions
- Immutability is encouraged by default
- Persistent Data Structures
- All values are immutable
- unless explicitly wrapped in an atom or ref
- state changes managed atomically (software transactional memory)
- core.async library allows you to write asynchronous code as easily as sequential
code
Using
persistent data structures
Iterate over collections
Generate new collections by applying functions
Sequence / List Comprehension
Iterate over collections
Sequence / List Comprehension
Iterating through a range of generated values to create a list of 2 value vectors
Immutability - local binding
Assignments made locally are immutable
- words is a local binding to the result of running the function upper-case on “Hello
World”
- letter->clack is a function that converts a character to a code
Lazy Evaluation
Only return a value when necessary
● maintain precision
● optimise evaluation
Lazy Evaluation
Clojure's lazy sequences
- returns a reference to a file and step through it one line at a time
- line-seq returns a lazy sequence of lines, so we can read files larger than
available memory, one line at a time
Polymorphism
Functions evaluate different algorithms based on arity of arguments
Recursion & Polymorphism
Process a collection of values by feeding the remaining elements back to the function
- the sum function is polymorphic, it has different behaviours that could be
evaluated depending on if passed 1 or 2 arguments
Recursion - tail call optimisation
Protect the heap space from blowing by using the recur function
Using recur in the last line is the same as calling sum, however the memory required
from the previous sum function call is over-written in memory. So only 1 memory slot
is used instead of 10 billion
Higher Order Functions
A function that takes one or more functions as arguments, or
a function that returns a function
Higher Order Functions
Functions always return a value & can be used as an argument to another function
Composing functions together
Example: current value of the Clojure project from the configuration file
- `slurp` in the project file, convert into a string and return the value at index 2
Design idiom:
Composing
functions
together
You can think of functional
design as evaluating one or
more functions in series of
functions
Functional Composition - map
Map the function inc over each number of the collection,
returns a new collection of numbers incremented by 1
Functional Composition - reduce
Reduce the numbers inside a collection to a single value by applying the + function,
returns a single value
Higher Order functions - partial, comp
Higher order functions can return a function
- The comp function composes other functions together
- The partial function allows you to lazily add another argument to a function
Managing State
State changes should be managed easily
Safe State changes
Changing state safely by not changing it
● Persistent data structures
● Local bindings
Changing state safely by changing it atomically
● Software Transactional Memory (STM)
○ Gives an mechanism like an in-memory atomic database that manages mutable state changes
under the covers
● Atoms
● core.async
Concurrency syntax - atoms
An online card game has players that can join and have their winnings tracked
Concurrency syntax - atoms
The join-game function adds players to the atom by their name, but only up to 2
players
Concurrency syntax - refs for sync updates
The join-game-safely adds players to the ref and alters their account & game account
Putting it all together
Let's find all the most common words used in a popular Science Fiction novel
Parallelism
Scale to the maximum
What is Parallelism
In simple terms: run the same code across multiple CPU’s
Parallelism - pmap
pmap - the same as map but in parallel
Parallelism - reduce
Significantly lower completion time running in parallel using Immutable data
structures
https://github.com/aphyr/tesser
Parallelism - reducers & folds
Tools to learn Clojure
inspire them & build up their motivation
Clojure support in many different tools
Leiningen - Clojure powered
build automation
LightTable - Instarepl
Emacs & Spacemacs
Figwheel (flappy birds example)
Examples, examples, examples
we learn by example...
Over 20 Books on Clojure...
Where to start with Clojure will be different...
Example:
I typically suggested BraveClojure.com as a starting
point, however many people prefer LivingClojure or
ClojureScript Unraveled...
Help people understand the relevance of a book and if
it's the right thing for them at that time.
Clojure.org & ClojureDocs.org
Github
Clojure-through-code Git repository
http://practical.li/clojure-webapps
Testing your Clojure skills...
Clojurian Community in Person
Probably the most active language-specific
developer communities in London
Learning by teaching others
I really started thinking in Clojure when I started talking to & teaching others
- Coding dojos
- talks on Clojure (starting with the basics, showing the art of the possible)
- moving on to running conferences
- workshops at hack days
Overtone live performance - MetaX
Overtone live performance - MetaX
Take your own journey into Clojure
Thank you
@jr0cket
jr0cket.co.uk
@jr0cket
@Heroku
@SalesforceDevs
#Trailhead
In a galaxy far, far away… London, UK

Thinking Functionally with Clojure

  • 1.
    Thinking Functionally with Clojure byJohn Stevenson @jr0cket www.practical.li
  • 3.
    Why Functional Programming it'snot just because it's really fun...
  • 4.
    Complex Systems … aresimply not easy to understand @jr0cket Josh Smith - Tweet Original Gif
  • 5.
    The Complexity Iceberg -@krisajenkins ● complexity is very dangerous when hidden ● You can't know what a function does for certain if it has side effects
  • 6.
    Side Effects Side Causesterm coined by @krisajenkins
  • 7.
    Pure Functions The resultsof the function are purely determined by its initial output and its own code - no external influence, a function only uses local values - referential transparency (the function can be replaced by its value)
  • 8.
    Impure Functions -side causes The results of the function are purely determined by its initial output and its own code - behaviour externally influenced and non-deterministic
  • 9.
    Eliminating Side Effects Functionalprogramming is about eliminating side effects where you can, controlling them where you can't - @krisajenkins The features in Functional Programming come from a desire to reduce side effects
  • 10.
    Clojure General purpose languagehosted on JVM, JavaScript & CLR
  • 11.
    Clojure / ClojureScript Ahosted language with simple interoperability with the host language - (java.Util.Date.) - (js/alert “Client side apps are easier in Clojure”)
  • 12.
    Clojure - basicsyntax for this talk ( ) ;; an empty list. The first element of a list is evaluated as a function call (function-name data) ;; call a function with the data as its argument (def name “data-or-value”) ;; assign (bind) a name to a data or legal value :keyword-name ;; a keyword is a name that points to itself ;; Thread-first macro - chain function calls, passing the result of each call as the first argument to the next function. The ,,, indicates where the resulting argument goes. (-> (function-a “data”) (function-b ,,,) ;; In Clojure commas , are whitespace (function-c ,,, “data”))
  • 13.
    Persistent data structures Built-inImmutability leading to deterministic code
  • 14.
    List, Vector, Map& Set Clojure’s built-in data structures are all immutable - returning a new data structure when a function is applied (list 1 2 3 4 5) ‘(“fish” “chips” 42) (vec ‘(1 2 3 4)) [1 2 3 4] {:key “value”} {:name “John” :skill “conferencing”} (set ‘(1 2 3 4 4)) #{1 2 3 4}
  • 15.
    Persistent Data Structures- shared memory Each function creates a new vector Memory space for values is shared between each vector
  • 16.
    Persistent Data Structures- shared memory By sharing memory you can apply functions over and over again effectively Values persist until they are no longer referenced
  • 17.
    Concurrency is Easier Concurrencyis much easier to write and reason about because of - Pure functions - Immutability is encouraged by default - Persistent Data Structures - All values are immutable - unless explicitly wrapped in an atom or ref - state changes managed atomically (software transactional memory) - core.async library allows you to write asynchronous code as easily as sequential code
  • 18.
    Using persistent data structures Iterateover collections Generate new collections by applying functions
  • 19.
    Sequence / ListComprehension Iterate over collections
  • 20.
    Sequence / ListComprehension Iterating through a range of generated values to create a list of 2 value vectors
  • 21.
    Immutability - localbinding Assignments made locally are immutable - words is a local binding to the result of running the function upper-case on “Hello World” - letter->clack is a function that converts a character to a code
  • 22.
    Lazy Evaluation Only returna value when necessary ● maintain precision ● optimise evaluation
  • 23.
    Lazy Evaluation Clojure's lazysequences - returns a reference to a file and step through it one line at a time - line-seq returns a lazy sequence of lines, so we can read files larger than available memory, one line at a time
  • 24.
    Polymorphism Functions evaluate differentalgorithms based on arity of arguments
  • 25.
    Recursion & Polymorphism Processa collection of values by feeding the remaining elements back to the function - the sum function is polymorphic, it has different behaviours that could be evaluated depending on if passed 1 or 2 arguments
  • 26.
    Recursion - tailcall optimisation Protect the heap space from blowing by using the recur function Using recur in the last line is the same as calling sum, however the memory required from the previous sum function call is over-written in memory. So only 1 memory slot is used instead of 10 billion
  • 27.
    Higher Order Functions Afunction that takes one or more functions as arguments, or a function that returns a function
  • 28.
    Higher Order Functions Functionsalways return a value & can be used as an argument to another function
  • 29.
    Composing functions together Example:current value of the Clojure project from the configuration file - `slurp` in the project file, convert into a string and return the value at index 2
  • 30.
    Design idiom: Composing functions together You canthink of functional design as evaluating one or more functions in series of functions
  • 31.
    Functional Composition -map Map the function inc over each number of the collection, returns a new collection of numbers incremented by 1
  • 32.
    Functional Composition -reduce Reduce the numbers inside a collection to a single value by applying the + function, returns a single value
  • 33.
    Higher Order functions- partial, comp Higher order functions can return a function - The comp function composes other functions together - The partial function allows you to lazily add another argument to a function
  • 34.
    Managing State State changesshould be managed easily
  • 35.
    Safe State changes Changingstate safely by not changing it ● Persistent data structures ● Local bindings Changing state safely by changing it atomically ● Software Transactional Memory (STM) ○ Gives an mechanism like an in-memory atomic database that manages mutable state changes under the covers ● Atoms ● core.async
  • 36.
    Concurrency syntax -atoms An online card game has players that can join and have their winnings tracked
  • 37.
    Concurrency syntax -atoms The join-game function adds players to the atom by their name, but only up to 2 players
  • 38.
    Concurrency syntax -refs for sync updates The join-game-safely adds players to the ref and alters their account & game account
  • 39.
    Putting it alltogether Let's find all the most common words used in a popular Science Fiction novel
  • 40.
  • 41.
    What is Parallelism Insimple terms: run the same code across multiple CPU’s
  • 42.
    Parallelism - pmap pmap- the same as map but in parallel
  • 43.
    Parallelism - reduce Significantlylower completion time running in parallel using Immutable data structures https://github.com/aphyr/tesser
  • 44.
  • 45.
    Tools to learnClojure inspire them & build up their motivation
  • 46.
    Clojure support inmany different tools
  • 47.
    Leiningen - Clojurepowered build automation
  • 49.
  • 50.
  • 51.
  • 53.
  • 54.
    Over 20 Bookson Clojure... Where to start with Clojure will be different... Example: I typically suggested BraveClojure.com as a starting point, however many people prefer LivingClojure or ClojureScript Unraveled... Help people understand the relevance of a book and if it's the right thing for them at that time.
  • 55.
  • 57.
  • 58.
  • 59.
  • 61.
  • 63.
    Clojurian Community inPerson Probably the most active language-specific developer communities in London
  • 64.
    Learning by teachingothers I really started thinking in Clojure when I started talking to & teaching others - Coding dojos - talks on Clojure (starting with the basics, showing the art of the possible) - moving on to running conferences - workshops at hack days
  • 65.
  • 66.
  • 67.
    Take your ownjourney into Clojure
  • 68.
  • 69.