SlideShare a Scribd company logo
1 of 74
Download to read offline
Clojure
“The Art of Abstraction”




                           Alex Miller
                           Revelytix
Why are We Here?
Why are We Here?

I think abstraction is central to what we
do as programmers.
Why are We Here?

I think abstraction is central to what we
do as programmers.
I think Clojure is a great language for
creating abstractions.
What is abstraction?
"Abstraction is the elimination of
the irrelevant and the amplification
of the essential."
- Bob Martin
"I've been doing a lot of abstract
painting lately... extremely abstract.
No brush, no paint, no canvas.
I just think about it."
- Steven Wright
Clojure

•A Lisp dialect on the JVM   (and CLR)



•Dynamically typed
•Compiled
"When we describe a language, we should pay
particular attention to the means that the language provides
  combining simple ideas to form more
for
complex ideas. Every powerful language has three
mechanisms for accomplishing this:

1. primitive expressions,
   which represent the simplest entities the language is concerned with

2. means of combination,
   by which compound elements are built from simpler ones

3. means of abstraction,
   by which compound elements can be named and manipulated as units "



   Structure and Interpretation of Computer Programs
      - Abelson, Sussman, Sussman
Primitive Expressions
           nil   nil

     numbers     1, 2.3, 22/7

       strings   "abc"

    characters   a, b, space

     symbols     math/fib

    keywords     :bar
Means of combination


         2 3
Means of combination


       + 2 3
Means of combination


     (+ 2 3)
      +   3
Means of combination

Expression
             (+ 2 3)
              +   3
Means of combination

Expression
             (+ 2 3)
              +   3

             Evaluate
Means of combination

Expression
             (+ 2 3)
              +   3

               Evaluate
Means of combination

Expression
             (+ 2 3)
              +   3

                 Evaluate
Means of combination

Expression
                 (+ 2 3)
                  +   3

        Invoke
Means of abstraction
        (fn [x] (* x x))
Means of abstraction
(def square (fn [x] (* x x)))
Means of abstraction
(def square (fn [x] (* x x)))

(defn square [x] (* x x))
Abstracting with
   functions
Abstracting with
      functions
(defn square [x] (* x x))
Abstracting with
      functions
(defn square [x] (* x x))
(defn cube   [x] (* x x x))
Abstracting with
      functions
(defn square [x] (* x x))
(defn cube   [x] (* x x x))

(defn exp    [x n]
  (apply * (repeat n x)))
Abstracting with
      functions
(defn exp [x n]
  (case n
        0 1
        1 x
        (* x (exp x (dec n)))))

(exp   2 3)
(* x   (exp 2 2))
(* x   (* x (exp 2 1)))
(* x   (* x x))
Abstracting with
         functions
(defn exp [x n]
  (loop [total 1
         counter n]
    (if (= counter 0)
      total
      (recur (* x total) (dec counter)))))
Abstracting with
   functions


   (defn exp [x n])
"It is better to have 100 functions
 operate on one data structure
 than to have 10 functions operate
 on 10 data structures."

- Alan J. Perlis
“Epigrams in Programming”
http://www.cs.yale.edu/quotes.html
Collections
  List   (1 2 3)

Vector   [1 2 3]

   Set   #{1 2 3}
 Map     {:a 1 :b 2 :c 3}
All data and
collections are
IMMUTABLE
All data and
collections are
IMMUTABLE
Structural sharing
(def a '(1 2 3))
Structural sharing
(def a '(1 2 3))
(def b (cons 4 a))
Structural sharing
(def a '(1 2 3))
(def b (cons 4 a))
(def c (cons 5 (rest a)))
What do all collections
 share in common?
What do all collections
 share in common?
 sequential traversal over values
What do all collections
 share in common?
 sequential traversal over values

             "seq"
Iterator Models
                          C#
        Java Iterator             Clojure seq
                      IEnumerator

more?    hasNext         MoveNext             not null

 get       next           Current               first

next       next          MoveNext               rest

           *table stolen from Rich Hickey’s talk on sequences
seq

vector      seq        first     rest
  nil        nil       nil       ()
             nil       nil       ()
12345
         (1 2 3 4 5)     1    (2 3 4 5)
Seq and ye shall find...
• String
• Java Collections
• Java Iterators (iterator-seq, enumeration-seq)
• ResultSet (resultset-seq)
• Trees (tree-seq)
• XML (xml-seq)
• Lines of a file (line-seq)
• Files in a directory (file-seq)
Lazy seqs

(take 10 (iterate inc 1))


(1 2 3 4 5 6 7 8 9 10)
Functions on
Collections and
  Sequences
Collection Traits
                                                                                 Reversible
                                                                                  Indexed
Sequential
                                                                                 Associative
 Counted
 Seqable     List                                                       Vector   Sequential
                                                                                  Counted
                                                            vector                Seqable
                      list            peek                    vec
                      list?           pop                  vector-of
                                      nth                   subvec
                                                            vector?



                                 replace
                                                              get
                                      conj
                                                             assoc
                                      first
                                                            dissoc
                                      count
                                                          select-keys
                                       seq

                                             contains?


                                                          hash-map
                                                         sorted-map find
                                                           zipmap   merge
                     hash-set                               keys merge-with
                    sorted-set                              vals
                       disj                                 map?


 Counted                                                                         Associative
 Seqable     Set                                                         Map      Counted
                                                                                  Seqable
Lists

(def a '(1 2 3))     #'user/a
(def b (cons 0 a))   #'user/b
(first b)            0
(rest b)             (1 2 3)
(count b)            4
(nth b 1)            1
Vectors

(def      v   [1 2 3])       #'user/v
(def      w   (conj v 4))    #'user/w
(nth      w   3)             4
(get      w   3)             4
  Vectors are
  associative -
indices are keys
Maps

(def m {:a 1 :b 2})      #'user/m
(def n (assoc m :c 3))   #'user/n
(keys n)                 (:c :a :b)
(vals n)                 (3 1 2)
(get m :a)               1
(m :a) Data as co de     1
(:a m)                   1
Sequence Functions
Sequence Functions

(range 6)                 (0 1 2 3 4 5)
(filter odd? (range 6))   (1 3 5)
(reverse (range 4))       (3 2 1 0)
(partition 2 (range 4))   ((0 1) (2 3))
(map inc (range 5))       (1 2 3 4 5)
(reduce + (range 10))     45
Higher order
      functions
(defn mult [x] (fn [y] (* x y)))
#'user/mult

(def x10 (mult 10))
#'user/x10

(map x10 (range 5))
(0 10 20 30 40)
Functional Kingdom
"In Javaland, by King Java's royal decree, Verbs are
owned by Nouns."

"In the Functional Kingdoms, Nouns and Verbs are
generally considered equal-caste citizens. However, the
Nouns, being, well, nouns, mostly sit around doing
nothing at all. They don't see much point in running or
executing anything, because the Verbs are quite active
and see to all that for them."


http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html
Data types
(def alex                         Person
                               first
  { :first "Alex"              last
                               eye-color
    :last "Miller"
    :eye-color :blue })
(:last alex)


(defrecord Person [first last eye-color])
(def alex (Person. "Alex" "Miller" :blue))
(:last alex)
Polymorphism
 relax    Programmer
         language




 relax    NormalPerson
         activity
Multimethods
(defrecord Programmer [language])
(defrecord NormalPerson [activity])

(defmulti relax class)
(defmethod relax Programmer [programmer]
  (println "I'm writing" (:language programmer)))
(defmethod relax NormalPerson [person]
  (println "I'm" (:activity person)))

(relax (Programmer. "Clojure"))
I'm writing Clojure
(relax (NormalPerson. "taking a walk"))
I'm taking a walk
Multimethods
(defrecord Programmer [language])

(defmulti quip :language)
(defmethod quip "Clojure" [programmer]
  (println "Running out of parens"))
(defmethod quip "Java" [programmer]
  (println "OOP rulez!"))

(relax (Programmer. "Clojure"))
Running out of parens
(relax (Programmer. "Java"))
OOP rulez!
Protocols
(defrecord Programmer [language])

(defprotocol Teacher
  (teach [p])
  (read [p]))

(extend-type Programmer
  Teacher
    (teach [p] (println "Teaching" (:language p)))
    (read [p] (println "Reading Hacker News")))

(teach (Programmer. "Clojure"))
Teaching Clojure
State


•Immutable data is great!
•But how do I maintain state and
  coordinate changes?
Epochal Model
                  of Time
                                 ge
                      State chan
                         function

                            ATM              ATM
                            -$60             -$60

Identity
    Checking   $120    Value          $60           $0




                                      Time
State Constructs
• Atoms - uncoordinated synchronous change
 • Like Atomic classes
• Refs - coordinated synchronous change
 • STM to coordinate changes across refs
• Agents - coordinated asynchronous change
 • Like actors but not "active" and state always
    visible to anyone
Macros
(defmacro and
  ([] true)
  ([x] x)
  ([x & next]
   `(let [and# ~x]
      (if and#
        (and ~@next)
        and#))))
Macros
(defmacro and          (and 1 2 3)
  ([] true)            (let* [i 1]
  ([x] x)                (if i
  ([x & next]              (let* [j 2]
   `(let [and# ~x]           (if j
      (if and#                   3
        (and ~@next)             j))
        and#))))           i))
Abstractions
• functions (name and manipulate code)
• collections (trait-based, immutable collections of data)
• seq (logical lists of values)
• records (data types)
• multimethods, protocols (polymorphism)
• atoms, refs, agents (state)
• macros (syntax, order of evaluation)
• namespaces (modularity)
• metadata (out-of-band information passing)
Incanter
(doto (function-plot pdf-normal
  (add-latex 0 0.1 eq)
Ring
Http request
{:protocol         :http
 :request-method   :get
 :uri              "/home"
 :server-name      "http://example.org"}


Http response
{:status 200
 :headers {"Content-Type" "text/plain"
           "Content Length" 11}
 :body    "Rainbows and unicorns"}
Hiccup
(html
  [:head
    [:title "My home page"]]
  [:body
    [:h1 "Links"]
    [:p [:a {:href "http://tech.puredanger.com"}
                   "Alex's blog"]])
Cascalog
• People in the Hadoop data set who are 25
  years old
    (?<- (stdout) [?person]
         (age ?person 25))


• Split sentences to words then count words
   (?<- (stdout) [?word ?count]
        (sentence ?s)
        (split ?s :> ?word)
        (c/count ?count))
Greenspun’s 10th
Rule of Programming

10) Any sufficiently complicated C or

Fortran program contains an ad hoc,

informally-specified, bug-ridden, slow

implementation of half of Common Lisp.
Corollaries

•Robert Morris’ corollary: “…including
  Common Lisp.”

•Norvig’s corollary: “Any sufficiently
  complicated LISP program is going to
  contain a slow implementation of half
  of Prolog”
Snowclones

•Orange is the new black
•GOTO considered harmful
•Got milk ?
•I’m a doctor, not a bricklayer
Snowclones

•Bacon is the new black
•Inheritance considered harmful
•Got nachos ?
•I’m a doctor, not a programmer
Words for snow
“If Eskimos have ___ words for snow,
___ surely have ___ words for ___.”
Words for snow
“If Eskimos have ___ words for snow,
___ surely have ___ words for ___.”



“If Eskimos have 100 words for snow,
programmers surely have 100 words for
abstraction.”
Sapir-Whorf
       hypothesis

Do the words we have available
determine what we are able to think?
Do the abstractions in our
language determine what
    we can program?
Thanks!

Blog: http://tech.puredanger.com

Twitter: @puredanger

Slides: http://slideshare.com/alexmiller/presentations

Strange Loop: http://thestrangeloop.com

More Related Content

What's hot (12)

Shoulder rehab early julia walton
Shoulder rehab early   julia waltonShoulder rehab early   julia walton
Shoulder rehab early julia walton
 
Violated by Cops Ch. 01
Violated by Cops Ch. 01
Violated by Cops Ch. 01
Violated by Cops Ch. 01
 
Girlfriend
GirlfriendGirlfriend
Girlfriend
 
cameltoes
cameltoescameltoes
cameltoes
 
Vampire
VampireVampire
Vampire
 
Sutra book-23-38
Sutra book-23-38Sutra book-23-38
Sutra book-23-38
 
Sexy women
Sexy womenSexy women
Sexy women
 
El Estrabismo 9844
El Estrabismo 9844El Estrabismo 9844
El Estrabismo 9844
 
The Shaman
The ShamanThe Shaman
The Shaman
 
Ch 8 slides_m
Ch 8 slides_mCh 8 slides_m
Ch 8 slides_m
 
Elegant Lust
Elegant LustElegant Lust
Elegant Lust
 
Ppt cam jm609
Ppt cam jm609Ppt cam jm609
Ppt cam jm609
 

Viewers also liked

Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developersJohn Stevenson
 
Cracking clojure
Cracking clojureCracking clojure
Cracking clojureAlex Miller
 
Clojure: an overview
Clojure: an overviewClojure: an overview
Clojure: an overviewLarry Diehl
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
Innovative Software
Innovative SoftwareInnovative Software
Innovative SoftwareAlex Miller
 
Caching In The Cloud
Caching In The CloudCaching In The Cloud
Caching In The CloudAlex Miller
 
Scaling Your Cache
Scaling Your CacheScaling Your Cache
Scaling Your CacheAlex Miller
 
Releasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebReleasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebAlex Miller
 
Stream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/joinStream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/joinAlex Miller
 
Project Fortress
Project FortressProject Fortress
Project FortressAlex Miller
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrencyAlex Miller
 
Scaling Hibernate with Terracotta
Scaling Hibernate with TerracottaScaling Hibernate with Terracotta
Scaling Hibernate with TerracottaAlex Miller
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Introthnetos
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data ScienceMike Anderson
 

Viewers also liked (20)

3 years with Clojure
3 years with Clojure3 years with Clojure
3 years with Clojure
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
Cracking clojure
Cracking clojureCracking clojure
Cracking clojure
 
Clojure: an overview
Clojure: an overviewClojure: an overview
Clojure: an overview
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
ETL in Clojure
ETL in ClojureETL in Clojure
ETL in Clojure
 
Innovative Software
Innovative SoftwareInnovative Software
Innovative Software
 
Caching In The Cloud
Caching In The CloudCaching In The Cloud
Caching In The Cloud
 
Scaling Your Cache
Scaling Your CacheScaling Your Cache
Scaling Your Cache
 
Releasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebReleasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic Web
 
Blogging ZOMG
Blogging ZOMGBlogging ZOMG
Blogging ZOMG
 
Stream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/joinStream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/join
 
Cold Hard Cache
Cold Hard CacheCold Hard Cache
Cold Hard Cache
 
Project Fortress
Project FortressProject Fortress
Project Fortress
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
Scaling Hibernate with Terracotta
Scaling Hibernate with TerracottaScaling Hibernate with Terracotta
Scaling Hibernate with Terracotta
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
 
DSL in Clojure
DSL in ClojureDSL in Clojure
DSL in Clojure
 

Similar to Clojure: The Art of Abstraction

Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collectionsKnoldus Inc.
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collectionsKnoldus Inc.
 
Scala collections wizardry - Scalapeño
Scala collections wizardry - ScalapeñoScala collections wizardry - Scalapeño
Scala collections wizardry - ScalapeñoSagie Davidovich
 
Леонид Шевцов «Clojure в деле»
Леонид Шевцов «Clojure в деле»Леонид Шевцов «Clojure в деле»
Леонид Шевцов «Clojure в деле»DataArt
 
Coffee script
Coffee scriptCoffee script
Coffee scripttimourian
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기JangHyuk You
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections LibraryPaul Phillips
 

Similar to Clojure: The Art of Abstraction (20)

Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
ML-CheatSheet (1).pdf
ML-CheatSheet (1).pdfML-CheatSheet (1).pdf
ML-CheatSheet (1).pdf
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
 
Scala collections wizardry - Scalapeño
Scala collections wizardry - ScalapeñoScala collections wizardry - Scalapeño
Scala collections wizardry - Scalapeño
 
Леонид Шевцов «Clojure в деле»
Леонид Шевцов «Clojure в деле»Леонид Шевцов «Clojure в деле»
Леонид Шевцов «Clojure в деле»
 
2.3 implicits
2.3 implicits2.3 implicits
2.3 implicits
 
Coffee script
Coffee scriptCoffee script
Coffee script
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기
 
Statistics lab 1
Statistics lab 1Statistics lab 1
Statistics lab 1
 
Scala collections
Scala collectionsScala collections
Scala collections
 
Scala Collections
Scala CollectionsScala Collections
Scala Collections
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Matlab tut3
Matlab tut3Matlab tut3
Matlab tut3
 
Map Reduce
Map ReduceMap Reduce
Map Reduce
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
 
Term Rewriting
Term RewritingTerm Rewriting
Term Rewriting
 
Commands list
Commands listCommands list
Commands list
 

More from Alex Miller

Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)Alex Miller
 
Concurrent Stream Processing
Concurrent Stream ProcessingConcurrent Stream Processing
Concurrent Stream ProcessingAlex Miller
 
Tree Editing with Zippers
Tree Editing with ZippersTree Editing with Zippers
Tree Editing with ZippersAlex Miller
 
Scaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At ScaleScaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At ScaleAlex Miller
 
Marshmallow Test
Marshmallow TestMarshmallow Test
Marshmallow TestAlex Miller
 
Strange Loop Conference 2009
Strange Loop Conference 2009Strange Loop Conference 2009
Strange Loop Conference 2009Alex Miller
 
Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex Miller
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns ReconsideredAlex Miller
 
Exploring Terracotta
Exploring TerracottaExploring Terracotta
Exploring TerracottaAlex Miller
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor ConcurrencyAlex Miller
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 

More from Alex Miller (13)

Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)
 
Concurrent Stream Processing
Concurrent Stream ProcessingConcurrent Stream Processing
Concurrent Stream Processing
 
Tree Editing with Zippers
Tree Editing with ZippersTree Editing with Zippers
Tree Editing with Zippers
 
Scaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At ScaleScaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At Scale
 
Marshmallow Test
Marshmallow TestMarshmallow Test
Marshmallow Test
 
Strange Loop Conference 2009
Strange Loop Conference 2009Strange Loop Conference 2009
Strange Loop Conference 2009
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns Reconsidered
 
Java 7 Preview
Java 7 PreviewJava 7 Preview
Java 7 Preview
 
Exploring Terracotta
Exploring TerracottaExploring Terracotta
Exploring Terracotta
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 

Recently uploaded

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 

Clojure: The Art of Abstraction

  • 1. Clojure “The Art of Abstraction” Alex Miller Revelytix
  • 2. Why are We Here?
  • 3. Why are We Here? I think abstraction is central to what we do as programmers.
  • 4. Why are We Here? I think abstraction is central to what we do as programmers. I think Clojure is a great language for creating abstractions.
  • 5. What is abstraction? "Abstraction is the elimination of the irrelevant and the amplification of the essential." - Bob Martin
  • 6. "I've been doing a lot of abstract painting lately... extremely abstract. No brush, no paint, no canvas. I just think about it." - Steven Wright
  • 7. Clojure •A Lisp dialect on the JVM (and CLR) •Dynamically typed •Compiled
  • 8. "When we describe a language, we should pay particular attention to the means that the language provides combining simple ideas to form more for complex ideas. Every powerful language has three mechanisms for accomplishing this: 1. primitive expressions, which represent the simplest entities the language is concerned with 2. means of combination, by which compound elements are built from simpler ones 3. means of abstraction, by which compound elements can be named and manipulated as units " Structure and Interpretation of Computer Programs - Abelson, Sussman, Sussman
  • 9. Primitive Expressions nil nil numbers 1, 2.3, 22/7 strings "abc" characters a, b, space symbols math/fib keywords :bar
  • 12. Means of combination (+ 2 3) + 3
  • 14. Means of combination Expression (+ 2 3) + 3 Evaluate
  • 15. Means of combination Expression (+ 2 3) + 3 Evaluate
  • 16. Means of combination Expression (+ 2 3) + 3 Evaluate
  • 17. Means of combination Expression (+ 2 3) + 3 Invoke
  • 18. Means of abstraction (fn [x] (* x x))
  • 19. Means of abstraction (def square (fn [x] (* x x)))
  • 20. Means of abstraction (def square (fn [x] (* x x))) (defn square [x] (* x x))
  • 21. Abstracting with functions
  • 22. Abstracting with functions (defn square [x] (* x x))
  • 23. Abstracting with functions (defn square [x] (* x x)) (defn cube [x] (* x x x))
  • 24. Abstracting with functions (defn square [x] (* x x)) (defn cube [x] (* x x x)) (defn exp [x n] (apply * (repeat n x)))
  • 25. Abstracting with functions (defn exp [x n] (case n 0 1 1 x (* x (exp x (dec n))))) (exp 2 3) (* x (exp 2 2)) (* x (* x (exp 2 1))) (* x (* x x))
  • 26. Abstracting with functions (defn exp [x n] (loop [total 1 counter n] (if (= counter 0) total (recur (* x total) (dec counter)))))
  • 27. Abstracting with functions (defn exp [x n])
  • 28. "It is better to have 100 functions operate on one data structure than to have 10 functions operate on 10 data structures." - Alan J. Perlis “Epigrams in Programming” http://www.cs.yale.edu/quotes.html
  • 29. Collections List (1 2 3) Vector [1 2 3] Set #{1 2 3} Map {:a 1 :b 2 :c 3}
  • 30. All data and collections are IMMUTABLE
  • 31. All data and collections are IMMUTABLE
  • 33. Structural sharing (def a '(1 2 3)) (def b (cons 4 a))
  • 34. Structural sharing (def a '(1 2 3)) (def b (cons 4 a)) (def c (cons 5 (rest a)))
  • 35. What do all collections share in common?
  • 36. What do all collections share in common? sequential traversal over values
  • 37. What do all collections share in common? sequential traversal over values "seq"
  • 38. Iterator Models C# Java Iterator Clojure seq IEnumerator more? hasNext MoveNext not null get next Current first next next MoveNext rest *table stolen from Rich Hickey’s talk on sequences
  • 39. seq vector seq first rest nil nil nil () nil nil () 12345 (1 2 3 4 5) 1 (2 3 4 5)
  • 40. Seq and ye shall find... • String • Java Collections • Java Iterators (iterator-seq, enumeration-seq) • ResultSet (resultset-seq) • Trees (tree-seq) • XML (xml-seq) • Lines of a file (line-seq) • Files in a directory (file-seq)
  • 41. Lazy seqs (take 10 (iterate inc 1)) (1 2 3 4 5 6 7 8 9 10)
  • 43. Collection Traits Reversible Indexed Sequential Associative Counted Seqable List Vector Sequential Counted vector Seqable list peek vec list? pop vector-of nth subvec vector? replace get conj assoc first dissoc count select-keys seq contains? hash-map sorted-map find zipmap merge hash-set keys merge-with sorted-set vals disj map? Counted Associative Seqable Set Map Counted Seqable
  • 44. Lists (def a '(1 2 3)) #'user/a (def b (cons 0 a)) #'user/b (first b) 0 (rest b) (1 2 3) (count b) 4 (nth b 1) 1
  • 45. Vectors (def v [1 2 3]) #'user/v (def w (conj v 4)) #'user/w (nth w 3) 4 (get w 3) 4 Vectors are associative - indices are keys
  • 46. Maps (def m {:a 1 :b 2}) #'user/m (def n (assoc m :c 3)) #'user/n (keys n) (:c :a :b) (vals n) (3 1 2) (get m :a) 1 (m :a) Data as co de 1 (:a m) 1
  • 48. Sequence Functions (range 6) (0 1 2 3 4 5) (filter odd? (range 6)) (1 3 5) (reverse (range 4)) (3 2 1 0) (partition 2 (range 4)) ((0 1) (2 3)) (map inc (range 5)) (1 2 3 4 5) (reduce + (range 10)) 45
  • 49. Higher order functions (defn mult [x] (fn [y] (* x y))) #'user/mult (def x10 (mult 10)) #'user/x10 (map x10 (range 5)) (0 10 20 30 40)
  • 50. Functional Kingdom "In Javaland, by King Java's royal decree, Verbs are owned by Nouns." "In the Functional Kingdoms, Nouns and Verbs are generally considered equal-caste citizens. However, the Nouns, being, well, nouns, mostly sit around doing nothing at all. They don't see much point in running or executing anything, because the Verbs are quite active and see to all that for them." http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html
  • 51. Data types (def alex Person first { :first "Alex" last eye-color :last "Miller" :eye-color :blue }) (:last alex) (defrecord Person [first last eye-color]) (def alex (Person. "Alex" "Miller" :blue)) (:last alex)
  • 52. Polymorphism relax Programmer language relax NormalPerson activity
  • 53. Multimethods (defrecord Programmer [language]) (defrecord NormalPerson [activity]) (defmulti relax class) (defmethod relax Programmer [programmer] (println "I'm writing" (:language programmer))) (defmethod relax NormalPerson [person] (println "I'm" (:activity person))) (relax (Programmer. "Clojure")) I'm writing Clojure (relax (NormalPerson. "taking a walk")) I'm taking a walk
  • 54. Multimethods (defrecord Programmer [language]) (defmulti quip :language) (defmethod quip "Clojure" [programmer] (println "Running out of parens")) (defmethod quip "Java" [programmer] (println "OOP rulez!")) (relax (Programmer. "Clojure")) Running out of parens (relax (Programmer. "Java")) OOP rulez!
  • 55. Protocols (defrecord Programmer [language]) (defprotocol Teacher (teach [p]) (read [p])) (extend-type Programmer Teacher (teach [p] (println "Teaching" (:language p))) (read [p] (println "Reading Hacker News"))) (teach (Programmer. "Clojure")) Teaching Clojure
  • 56. State •Immutable data is great! •But how do I maintain state and coordinate changes?
  • 57. Epochal Model of Time ge State chan function ATM ATM -$60 -$60 Identity Checking $120 Value $60 $0 Time
  • 58. State Constructs • Atoms - uncoordinated synchronous change • Like Atomic classes • Refs - coordinated synchronous change • STM to coordinate changes across refs • Agents - coordinated asynchronous change • Like actors but not "active" and state always visible to anyone
  • 59. Macros (defmacro and ([] true) ([x] x) ([x & next] `(let [and# ~x] (if and# (and ~@next) and#))))
  • 60. Macros (defmacro and (and 1 2 3) ([] true) (let* [i 1] ([x] x) (if i ([x & next] (let* [j 2] `(let [and# ~x] (if j (if and# 3 (and ~@next) j)) and#)))) i))
  • 61. Abstractions • functions (name and manipulate code) • collections (trait-based, immutable collections of data) • seq (logical lists of values) • records (data types) • multimethods, protocols (polymorphism) • atoms, refs, agents (state) • macros (syntax, order of evaluation) • namespaces (modularity) • metadata (out-of-band information passing)
  • 63. Ring Http request {:protocol :http :request-method :get :uri "/home" :server-name "http://example.org"} Http response {:status 200 :headers {"Content-Type" "text/plain" "Content Length" 11} :body "Rainbows and unicorns"}
  • 64. Hiccup (html [:head [:title "My home page"]] [:body [:h1 "Links"] [:p [:a {:href "http://tech.puredanger.com"} "Alex's blog"]])
  • 65. Cascalog • People in the Hadoop data set who are 25 years old (?<- (stdout) [?person] (age ?person 25)) • Split sentences to words then count words (?<- (stdout) [?word ?count] (sentence ?s) (split ?s :> ?word) (c/count ?count))
  • 66. Greenspun’s 10th Rule of Programming 10) Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.
  • 67. Corollaries •Robert Morris’ corollary: “…including Common Lisp.” •Norvig’s corollary: “Any sufficiently complicated LISP program is going to contain a slow implementation of half of Prolog”
  • 68. Snowclones •Orange is the new black •GOTO considered harmful •Got milk ? •I’m a doctor, not a bricklayer
  • 69. Snowclones •Bacon is the new black •Inheritance considered harmful •Got nachos ? •I’m a doctor, not a programmer
  • 70. Words for snow “If Eskimos have ___ words for snow, ___ surely have ___ words for ___.”
  • 71. Words for snow “If Eskimos have ___ words for snow, ___ surely have ___ words for ___.” “If Eskimos have 100 words for snow, programmers surely have 100 words for abstraction.”
  • 72. Sapir-Whorf hypothesis Do the words we have available determine what we are able to think?
  • 73. Do the abstractions in our language determine what we can program?
  • 74. Thanks! Blog: http://tech.puredanger.com Twitter: @puredanger Slides: http://slideshare.com/alexmiller/presentations Strange Loop: http://thestrangeloop.com