SlideShare une entreprise Scribd logo
1  sur  74
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
Hash tables and hash maps in python | Edureka
Hash tables and hash maps in python | EdurekaHash tables and hash maps in python | Edureka
Hash tables and hash maps in python | EdurekaEdureka!
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword pptVinod Kumar
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaEdureka!
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaJorge Vásquez
 
Class as the basis of all computation
Class as the basis of all computationClass as the basis of all computation
Class as the basis of all computationabhijeetkumarkar422
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sortingKaushal Shah
 
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...Ruby Meditation
 
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in pythonSangita Panchal
 
Radix and Shell sort
Radix and Shell sortRadix and Shell sort
Radix and Shell sorthannatamayao
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular ExpressionMasudul Haque
 
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...Philip Schwarz
 

Tendances (20)

Merge sort
Merge sortMerge sort
Merge sort
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Hash tables and hash maps in python | Edureka
Hash tables and hash maps in python | EdurekaHash tables and hash maps in python | Edureka
Hash tables and hash maps in python | Edureka
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Awt
AwtAwt
Awt
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
 
Class as the basis of all computation
Class as the basis of all computationClass as the basis of all computation
Class as the basis of all computation
 
JQuery selectors
JQuery selectors JQuery selectors
JQuery selectors
 
Sets in python
Sets in pythonSets in python
Sets in python
 
sorting and its types
sorting and its typessorting and its types
sorting and its types
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sorting
 
Big O Notation
Big O NotationBig O Notation
Big O Notation
 
14 Skip Lists
14 Skip Lists14 Skip Lists
14 Skip Lists
 
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...
 
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in python
 
Radix and Shell sort
Radix and Shell sortRadix and Shell sort
Radix and Shell sort
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular Expression
 
Quick sort
Quick sortQuick sort
Quick sort
 
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer 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