SlideShare a Scribd company logo
ma de
r e a lly r e a lly
                      Ta l k
     s im p le
W h y C lo ju r e ?
Why get functional ?
4 cores in a Mac book Pro for developers
W h a t is
C lo ju r e
Clojure made really really simple
Clojure made really really simple
Clojure is small and flexible
Clojure concepts
Encourages Pure Functional approach
- use STM to change state


Functions as first class citizens
  - functions as arguments as they return a value


Make JVM interoperation simple
  - easy to use your existing Java applications
A better Lisp !
Sensible () usage


Sensible macro names


JVM Interoperability
Which LISP is your wingman ?
Common Lisp        Clojure
The dark side of Clojure



         ( x )
The dark side of Clojure



      ( ( x ) )
The dark side of Clojure



    ( ( ( x ) ) )
The dark side of Clojure



 ( ( ( ( x ) ) ) )
The dark side of Clojure



( ( ( ( ( x ) ) ) ) )
...verses non-lisp languages




      ( ) ==
     { ( ) };
Well nearly....


 ([] ((())))
        ==
{ ( {( []) }) };
C o m p a r in g
    J a va
    w it h
  C lo ju r e
It s a ll b y t e c o d e in t h e
               e nd ..
Any object in clojure is just a regular java object




A reference type inheriting from:
         j ava. l ang. obj ec t
Clojure made really really simple
Prefix notation



( def n s quar e- t he- number
  [ x]
    ( * x x) )
Im m u t a b le
    D a ta
s truc ture s
List – Ordered collection

( l i s t 1 3 5 7)

' ( 1 3 5 7)

 ( 1 2 3) ; 1 i s n o t a
  f unct i on
Vectors – hashed ordered list
[ : m r i x- c har ac t er s [ : neo
     at
   : m pheus : t r i ni t y : s m t h] ]
      or                          i


( f i r s t [ : n e o : mo r p h e u s : t r i n i t y
   : s mi t h ] )


( nt h [ : mat r i x : b ab yl o n 5 : f i r e f l y
  : s t ar g at e ] 2 )


( c onc at [ : n e o ] [ : t r i n i t y] )
Maps – unordered key/values
{ : a 1 : b 2}                                { : a { : a 1} }
    { : a 1 , : b 2}                             {: a {: a 1}}


{ :a 1 :b }                                   { { : a 1} : a}
j ava. l an g . Ar r ayI n d e x Ou t Of Bo      { { : a 1 } : a}
   u n d s Ex c e p t i o n : 3
                                              ; i d i om - put : a on t he
                                                left
{ : a 1 : b 2}
    { : a 1 , : b 2}
L is t s a r e f o r
       c ode

Ve c t o r s a r e
  fo r d a ta
Defining a data structure
( def m dat a- s t r uc t ur e
        y-
 [ dat a ] )

( def days - of - t he- week
  [ “Monday” “ Tues day”
 “W ednes day” ] )
Example data structure


( def j r 0c ket
   { : f i r s t - nam " J ohn" ,
                      e

    : l as t - name
 " St evens on" } )
G e t c o d in g !
c lo ju r e .
           org
d o c s . c lo ju r
     e .o rg
All hail the REPL
An interactive shell for
 clojure

Fast feedback loop
 for clojure
Clojure made really really simple
Clojure made really really simple
M a n a g in g a
   c lo ju r e
   p r o je c t
Maven
Just like any other Java project


Step 1)
Add Clojure library jar to your POM


Step 2)
Download the Internet !!!
le in in g e n
   Leiningen
                               .o rg




lein new     Create a new clojure project
lein deps    Download all dependencies
lein repl    Start the interactive shell (repl)
lein swank   Start repl server
Clojure made really really simple
Ema c s
Clojure made really really simple
Clojure made really really simple
A fe w
in t e r e s t in g
   C lo ju r e
 e x a m p le s
Ratio
Unique data type            (/ 2 4)
                            (/ 2.0 4)
Allow lazy evaluation
                            (/ 1 3)
Avoid loss of precision     (/ 1.0 3)


                            (class (/ 1 3)
Calling Java... ooooo!!
( j avax . s wi n g . JOp t i o n Pan e /
    s h o wMe s s ag e D i al o g n i l
        " He l l o W r l d " )
                     o
Importing Java into Clojure
( ns dr aw ng- dem
          i       o
   ( : i m t [ j avax. s w ng J panel
          por             i
 J Fr am  e]
            [ j ava. awt
 Di m i on] ) )
     ens
Working with Java
Java Classes
  fullstop after class name
  ( J Fr am )
           e.
  (Math/cos 3) ; static method call

Java methods
  fullstop before method name
  ( . get Cont ent Pane f r am ;;method name first
                              e)
  ( . f r am get Cont ent Pane) ;;object first
            e
What class is that...
(class (str "Jr0cket"))
java.lang.String


(class (defn hello-world [name] (str "Hello
  cruel world")))
clojure.lang.Var
Clojure calling Java web stuff
( l et [ c onn]
    ( dot o ( Ht t pUr l Connec t i on.
  Ur l )
       ( . s et Reques t M hod
                          et
     “ POST” )
       ( . s et DoOut put t r ue)

   ( . s et I ns t aneFol l ow   Redi r ec t
   s                 t r ue) ) ] )
Recursive functions
Functions that call   Tail recursion
 themselves           Avoids blowing the
                       stack
Fractal coding
                      A trick as the JVM does
                       not support tail
                       recursion directly :-(
Tail recursion
( def n r ec ur s i ve- c ount er
   ( pr i nt ans w )er
   ( i f ( < ans w  er 1000)
     (   r ec ur   ( + ans wer 4) ) ) )
Where to find out more...


c l oj ur e. or g/ c heat s h
             eet
M u t a b le S t a t e
Software Transactional Memory

Provides safe, concurrent access to memory


Agents allow encapsulated access to mutable
 resources
F u n c t io n a l
     We b
Noir   w e b n o ir . o r g
Th a n k yo u
    London Cl oj ur i ans




c l oj ur e. or g
                    @ r 0c ket
                     j

More Related Content

Clojure made really really simple

  • 1. ma de r e a lly r e a lly Ta l k s im p le
  • 2. W h y C lo ju r e ?
  • 3. Why get functional ? 4 cores in a Mac book Pro for developers
  • 4. W h a t is C lo ju r e
  • 7. Clojure is small and flexible
  • 8. Clojure concepts Encourages Pure Functional approach - use STM to change state Functions as first class citizens - functions as arguments as they return a value Make JVM interoperation simple - easy to use your existing Java applications
  • 9. A better Lisp ! Sensible () usage Sensible macro names JVM Interoperability
  • 10. Which LISP is your wingman ? Common Lisp Clojure
  • 11. The dark side of Clojure ( x )
  • 12. The dark side of Clojure ( ( x ) )
  • 13. The dark side of Clojure ( ( ( x ) ) )
  • 14. The dark side of Clojure ( ( ( ( x ) ) ) )
  • 15. The dark side of Clojure ( ( ( ( ( x ) ) ) ) )
  • 16. ...verses non-lisp languages ( ) == { ( ) };
  • 17. Well nearly.... ([] ((()))) == { ( {( []) }) };
  • 18. C o m p a r in g J a va w it h C lo ju r e
  • 19. It s a ll b y t e c o d e in t h e e nd .. Any object in clojure is just a regular java object A reference type inheriting from: j ava. l ang. obj ec t
  • 21. Prefix notation ( def n s quar e- t he- number [ x] ( * x x) )
  • 22. Im m u t a b le D a ta s truc ture s
  • 23. List – Ordered collection ( l i s t 1 3 5 7) ' ( 1 3 5 7) ( 1 2 3) ; 1 i s n o t a f unct i on
  • 24. Vectors – hashed ordered list [ : m r i x- c har ac t er s [ : neo at : m pheus : t r i ni t y : s m t h] ] or i ( f i r s t [ : n e o : mo r p h e u s : t r i n i t y : s mi t h ] ) ( nt h [ : mat r i x : b ab yl o n 5 : f i r e f l y : s t ar g at e ] 2 ) ( c onc at [ : n e o ] [ : t r i n i t y] )
  • 25. Maps – unordered key/values { : a 1 : b 2} { : a { : a 1} } { : a 1 , : b 2} {: a {: a 1}} { :a 1 :b } { { : a 1} : a} j ava. l an g . Ar r ayI n d e x Ou t Of Bo { { : a 1 } : a} u n d s Ex c e p t i o n : 3 ; i d i om - put : a on t he left { : a 1 : b 2} { : a 1 , : b 2}
  • 26. L is t s a r e f o r c ode Ve c t o r s a r e fo r d a ta
  • 27. Defining a data structure ( def m dat a- s t r uc t ur e y- [ dat a ] ) ( def days - of - t he- week [ “Monday” “ Tues day” “W ednes day” ] )
  • 28. Example data structure ( def j r 0c ket { : f i r s t - nam " J ohn" , e : l as t - name " St evens on" } )
  • 29. G e t c o d in g !
  • 30. c lo ju r e . org d o c s . c lo ju r e .o rg
  • 31. All hail the REPL An interactive shell for clojure Fast feedback loop for clojure
  • 34. M a n a g in g a c lo ju r e p r o je c t
  • 35. Maven Just like any other Java project Step 1) Add Clojure library jar to your POM Step 2) Download the Internet !!!
  • 36. le in in g e n Leiningen .o rg lein new Create a new clojure project lein deps Download all dependencies lein repl Start the interactive shell (repl) lein swank Start repl server
  • 41. A fe w in t e r e s t in g C lo ju r e e x a m p le s
  • 42. Ratio Unique data type (/ 2 4) (/ 2.0 4) Allow lazy evaluation (/ 1 3) Avoid loss of precision (/ 1.0 3) (class (/ 1 3)
  • 43. Calling Java... ooooo!! ( j avax . s wi n g . JOp t i o n Pan e / s h o wMe s s ag e D i al o g n i l " He l l o W r l d " ) o
  • 44. Importing Java into Clojure ( ns dr aw ng- dem i o ( : i m t [ j avax. s w ng J panel por i J Fr am e] [ j ava. awt Di m i on] ) ) ens
  • 45. Working with Java Java Classes fullstop after class name ( J Fr am ) e. (Math/cos 3) ; static method call Java methods fullstop before method name ( . get Cont ent Pane f r am ;;method name first e) ( . f r am get Cont ent Pane) ;;object first e
  • 46. What class is that... (class (str "Jr0cket")) java.lang.String (class (defn hello-world [name] (str "Hello cruel world"))) clojure.lang.Var
  • 47. Clojure calling Java web stuff ( l et [ c onn] ( dot o ( Ht t pUr l Connec t i on. Ur l ) ( . s et Reques t M hod et “ POST” ) ( . s et DoOut put t r ue) ( . s et I ns t aneFol l ow Redi r ec t s t r ue) ) ] )
  • 48. Recursive functions Functions that call Tail recursion themselves Avoids blowing the stack Fractal coding A trick as the JVM does not support tail recursion directly :-(
  • 49. Tail recursion ( def n r ec ur s i ve- c ount er ( pr i nt ans w )er ( i f ( < ans w er 1000) ( r ec ur ( + ans wer 4) ) ) )
  • 50. Where to find out more... c l oj ur e. or g/ c heat s h eet
  • 51. M u t a b le S t a t e
  • 52. Software Transactional Memory Provides safe, concurrent access to memory Agents allow encapsulated access to mutable resources
  • 53. F u n c t io n a l We b
  • 54. Noir w e b n o ir . o r g
  • 55. Th a n k yo u London Cl oj ur i ans c l oj ur e. or g @ r 0c ket j

Editor's Notes

  1. Clock speeds peeks at ~3GHz in 2005 Moores law - now about CPU cores Laptops with 128 cores by 2020 ?? Parallelism over Concurrency at the hardware level Not just multi-threading and hyper-threading
  2. Hickey&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.
  3. 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
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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&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&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&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!
  10. Hiccup library for representing HTML in Clojure. It uses vectors to represent tags, and maps to represent a tag&apos;s attributes.