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

Data Modeling & Metadata for Graph Databases
Data Modeling & Metadata for Graph DatabasesData Modeling & Metadata for Graph Databases
Data Modeling & Metadata for Graph DatabasesDATAVERSITY
 
Cassandra sharding and consistency (lightning talk)
Cassandra sharding and consistency (lightning talk)Cassandra sharding and consistency (lightning talk)
Cassandra sharding and consistency (lightning talk)Federico Razzoli
 
Terasort
TerasortTerasort
Terasorthhyin
 
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...Julian Hyde
 
Object Oriented Modeling and Design with UML
Object Oriented Modeling and Design with UMLObject Oriented Modeling and Design with UML
Object Oriented Modeling and Design with UMLMalek Sumaiya
 
Lecture11 use case sequence diagram
Lecture11 use case sequence diagramLecture11 use case sequence diagram
Lecture11 use case sequence diagramShahid Riaz
 
JSON and the Oracle Database
JSON and the Oracle DatabaseJSON and the Oracle Database
JSON and the Oracle DatabaseMaria Colgan
 
Don’t optimize my queries, optimize my data!
Don’t optimize my queries, optimize my data!Don’t optimize my queries, optimize my data!
Don’t optimize my queries, optimize my data!Julian Hyde
 
Source code visualization (SourceViz)
Source code visualization (SourceViz)Source code visualization (SourceViz)
Source code visualization (SourceViz)Anas Bilal
 
The Challenges of Distributing Postgres: A Citus Story | DataEngConf NYC 2017...
The Challenges of Distributing Postgres: A Citus Story | DataEngConf NYC 2017...The Challenges of Distributing Postgres: A Citus Story | DataEngConf NYC 2017...
The Challenges of Distributing Postgres: A Citus Story | DataEngConf NYC 2017...Citus Data
 
Ooad (object oriented analysis design)
Ooad (object oriented analysis design)Ooad (object oriented analysis design)
Ooad (object oriented analysis design)Gagandeep Nanda
 
AgensGraph: a Multi-model Graph Database based on PostgreSql
AgensGraph: a Multi-model Graph Database based on PostgreSqlAgensGraph: a Multi-model Graph Database based on PostgreSql
AgensGraph: a Multi-model Graph Database based on PostgreSqlKisung Kim
 

What's hot (20)

XSLT presentation
XSLT presentationXSLT presentation
XSLT presentation
 
Data Modeling & Metadata for Graph Databases
Data Modeling & Metadata for Graph DatabasesData Modeling & Metadata for Graph Databases
Data Modeling & Metadata for Graph Databases
 
Cassandra sharding and consistency (lightning talk)
Cassandra sharding and consistency (lightning talk)Cassandra sharding and consistency (lightning talk)
Cassandra sharding and consistency (lightning talk)
 
Terasort
TerasortTerasort
Terasort
 
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
Planning with Polyalgebra: Bringing Together Relational, Complex and Machine ...
 
Uml introduciton
Uml introducitonUml introduciton
Uml introduciton
 
Css properties
Css propertiesCss properties
Css properties
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Object Oriented Modeling and Design with UML
Object Oriented Modeling and Design with UMLObject Oriented Modeling and Design with UML
Object Oriented Modeling and Design with UML
 
html-css
html-csshtml-css
html-css
 
Xml Schema
Xml SchemaXml Schema
Xml Schema
 
Elasticsearch
ElasticsearchElasticsearch
Elasticsearch
 
Lecture11 use case sequence diagram
Lecture11 use case sequence diagramLecture11 use case sequence diagram
Lecture11 use case sequence diagram
 
Css properties
Css propertiesCss properties
Css properties
 
JSON and the Oracle Database
JSON and the Oracle DatabaseJSON and the Oracle Database
JSON and the Oracle Database
 
Don’t optimize my queries, optimize my data!
Don’t optimize my queries, optimize my data!Don’t optimize my queries, optimize my data!
Don’t optimize my queries, optimize my data!
 
Source code visualization (SourceViz)
Source code visualization (SourceViz)Source code visualization (SourceViz)
Source code visualization (SourceViz)
 
The Challenges of Distributing Postgres: A Citus Story | DataEngConf NYC 2017...
The Challenges of Distributing Postgres: A Citus Story | DataEngConf NYC 2017...The Challenges of Distributing Postgres: A Citus Story | DataEngConf NYC 2017...
The Challenges of Distributing Postgres: A Citus Story | DataEngConf NYC 2017...
 
Ooad (object oriented analysis design)
Ooad (object oriented analysis design)Ooad (object oriented analysis design)
Ooad (object oriented analysis design)
 
AgensGraph: a Multi-model Graph Database based on PostgreSql
AgensGraph: a Multi-model Graph Database based on PostgreSqlAgensGraph: a Multi-model Graph Database based on PostgreSql
AgensGraph: a Multi-model Graph Database based on PostgreSql
 

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

Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...amber724300
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
WomenInAutomation2024: AI and Automation for eveyone
WomenInAutomation2024: AI and Automation for eveyoneWomenInAutomation2024: AI and Automation for eveyone
WomenInAutomation2024: AI and Automation for eveyoneUiPathCommunity
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 

Recently uploaded (20)

Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
WomenInAutomation2024: AI and Automation for eveyone
WomenInAutomation2024: AI and Automation for eveyoneWomenInAutomation2024: AI and Automation for eveyone
WomenInAutomation2024: AI and Automation for eveyone
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 

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