Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

Clojure values

1.071 Aufrufe

Veröffentlicht am

Veröffentlicht in: Technologie, Business
  • Als Erste(r) kommentieren

Clojure values

  1. 1. Thinking theClojure Way Christophe GrandGOTO Cph, May 13th 2011
  2. 2. Rejoice, Clojure is simple Coding along/against Singing with à la carte
  3. 3. Rejoice, Clojure is simple Coding along/against Singing with Small regular syntax à la carte
  4. 4. Rejoice, Clojure is simple Coding along/against Singing with Small regular syntax à la carte Simple does not mean familiar
  5. 5. Rejoice, Clojure is simple Coding along/against Singing with Small regular syntax à la carte Simple does not mean familiar Simple means not compound
  6. 6. Rejoice, Clojure is simple Coding along/against Singing with Small regular syntax à la carte Simple does not mean familiar Simple means not compound Clojure is made of simple things
  7. 7. Rejoice, Clojure is simple Coding along/against Singing with Small regular syntax à la carte Simple does not mean familiar Simple means not compound Clojure is made of simple things Small set of independent concepts
  8. 8. Rejoice, Clojure is simple Coding along/against Singing with Small regular syntax à la carte Simple does not mean familiar Simple means not compound Clojure is made of simple things Small set of independent concepts One concept at a time
  9. 9. Rejoice, Clojure is simple Coding along/against Singing with Small regular syntax à la carte Simple does not mean familiar Simple means not compound Clojure is made of simple things Small set of independent concepts One concept at a time
  10. 10. One bite at a time faire 4 groupes : Syntax+FP Rec+lazy seqs polymorphism+typesSyntax interop+mutation les deux derniers blocs devraient être animés pour être mis au même niveauCore Functional ProgrammingRecursion and loopsLazy seqs (creating your owns)PolymorphismTypesMacrosInteropState management
  11. 11. Syntax
  12. 12. LiteralsNumbers 42 3.14 3/4 5.01M 43N Strings "Hello GOTO Cph"Characters c newlineKeywords :a-key Symbols foo clojure.core/map Vectors [1 "two" :three] Maps {:key "val", :key2 42} Sets #{1 "two" :three} Regex #"a.*b" null nilbooleans* true false *anything but false and nil is true
  13. 13. What about lists?
  14. 14. What about lists?Quoted lists are too literal: (1 (+ 1 1))
  15. 15. What about lists?Quoted lists are too literal: (1 (+ 1 1))Displaced as literals by vectors
  16. 16. What about lists?Quoted lists are too literal: (1 (+ 1 1))Displaced as literals by vectorsAbstracted away by sequences
  17. 17. What about lists?Quoted lists are too literal: (1 (+ 1 1))Displaced as literals by vectorsAbstracted away by sequencesSurvive mostly for code representation
  18. 18. Lists are for code (defn abs [n] (if (neg? n) (- n) n))
  19. 19. Lists are for code (defn abs [n] (if (neg? n) (- n) n))Pro tip: Lisp code is a stereogram
  20. 20. Lists are for code (defn abs [n] (if (neg? n) (- n) n)) Pro tip: Lisp code is a stereogramCross your eyes to see parens in the right place
  21. 21. Lists are for code defn abs [n]( if neg?( n)( -( n) n)) Pro tip: Lisp code is a stereogramCross your eyes to see parens in the right place
  22. 22. Lists are for code (defn abs [n] (if (neg? n) (- n) n))
  23. 23. Lists are for code (defn abs [n] (if (neg? n) (- n) n)) function
  24. 24. Lists are for code (defn abs [n]macro (if (neg? n) (- n) n)) function
  25. 25. Lists are for code (defn abs [n]macro (if (neg? n) (- n) n)) functionspecial form
  26. 26. That’s all about syntax!
  27. 27. FunctionalProgramming
  28. 28. Clojure’s FP
  29. 29. Clojure’s FPImpure
  30. 30. Clojure’s FPImpurePersistent collections
  31. 31. Clojure’s FPImpurePersistent collectionsStrictly evaluated
  32. 32. Clojure’s FPImpurePersistent collectionsStrictly evaluatedBut lazy sequences
  33. 33. Clojure’s FPImpurePersistent collectionsStrictly evaluatedBut lazy sequences Not strictly lazy though!
  34. 34. Clojure’s FPImpurePersistent collectionsStrictly evaluatedBut lazy sequences Not strictly lazy though!
  35. 35. Persistent collections
  36. 36. Persistent collectionsVectors, maps and sets
  37. 37. Persistent collectionsVectors, maps and setsCommon usecases:
  38. 38. Persistent collectionsVectors, maps and setsCommon usecases: Vectors as tuples
  39. 39. Persistent collectionsVectors, maps and setsCommon usecases: Vectors as tuples Vectors as stacks
  40. 40. Persistent collectionsVectors, maps and setsCommon usecases: Vectors as tuples Vectors as stacks Maps as data
  41. 41. Persistent collectionsVectors, maps and setsCommon usecases: Vectors as tuples Vectors as stacks Maps as data Map as index, summary
  42. 42. Persistent collectionsVectors, maps and setsCommon usecases: Vectors as tuples Vectors as stacks Maps as data Map as index, summary Sets as containers, relations
  43. 43. Sequences
  44. 44. SequencesFirst, what are sequences?
  45. 45. SequencesFirst, what are sequences?Abstraction over linked lists
  46. 46. SequencesFirst, what are sequences?Abstraction over linked listsList-like views over data
  47. 47. SequencesFirst, what are sequences?Abstraction over linked listsList-like views over data Support first and rest
  48. 48. SequencesFirst, what are sequences?Abstraction over linked listsList-like views over data Support first and rest Replace iterators
  49. 49. SequencesFirst, what are sequences?Abstraction over linked listsList-like views over data Support first and rest Replace iterators Replace indices
  50. 50. Lazy sequences
  51. 51. Lazy sequencesSequences evaluated (realized) on demand
  52. 52. Lazy sequencesSequences evaluated (realized) on demandAllow to process big data
  53. 53. Lazy sequencesSequences evaluated (realized) on demandAllow to process big data or big intermediate values
  54. 54. Lazy sequences Sequences evaluated (realized) on demand Allow to process big data or big intermediate values(->> (slurp "access.log") split-lines (map count) (filter odd?))
  55. 55. Lazy sequences Doesn’t matter w/ strict evaluation
  56. 56. Lazy sequencesRealization can go ahead of consumption Doesn’t matter w/ strict evaluation
  57. 57. Lazy sequencesRealization can go ahead of consumption Not suitable for control flow Doesn’t matter w/ strict evaluation
  58. 58. Lazy sequencesRealization can go ahead of consumption Not suitable for control flow Doesn’t matter w/ strict evaluation Better locality, less churn
  59. 59. That’s all about FP!
  60. 60. Clojure spirit
  61. 61. Clojure spirit
  62. 62. Clojure spiritPragmatism
  63. 63. Clojure spiritPragmatismCorrectness
  64. 64. Clojure spiritPragmatismCorrectnessUniform interfaces
  65. 65. Clojure spiritPragmatismCorrectnessUniform interfacesData over functions
  66. 66. Clojure spiritPragmatismCorrectnessUniform interfacesData over functionsSequences as computation media
  67. 67. Clojure spiritPragmatismCorrectnessUniform interfacesData over functionsSequences as computation mediaReftypes as mutation patterns
  68. 68. PragmatismHosted on the JVMEmbrace the host limitations to be a better guestExcellent Java interopPerformance over purityLISP
  69. 69. CorrectnessNo silent errorCorrect result or failureNon-negotiable See 1.2 -> 1.3 numerics changes Unless the user opts in
  70. 70. Uniform interfaces
  71. 71. Uniform interfacesWidespread small interfaces
  72. 72. Uniform interfacesWidespread small interfacesTons of helpers fns built upon
  73. 73. Uniform interfacesWidespread small interfacesTons of helpers fns built uponIt is better to have 100 functions operate onone data structure than 10 functions on 10data structures. – Alan Perlis
  74. 74. Uniform interfacesWidespread small interfacesTons of helpers fns built uponIt is better to have 100 functions operate onone data structure than 10 functions on 10data structures. – Alan PerlisIt is better to have 100 functions operate onone abstraction than 10 functions on 10data structures. – Rich Hickey
  75. 75. Uniform interfaces=> (-> {:product-id "ACME123", :description "Powderwater"} keys sort)(:description :product-id)=> (-> (javax.swing.JFrame.) bean keys sort)(:JMenuBar :accessibleContext :active :alignmentX:alignmentY :alwaysOnTop :alwaysOnTopSupported:background :bufferStrategy :componentCount :components:containerListeners :contentPane :cursorType:defaultCloseOperation ...)
  76. 76. Data over functionsLarge reuse of core collection fns Less specific codeData go out of the process Don’t be too cleverA schema is a good API
  77. 77. Data over functions
  78. 78. Data over functionsHow to enforce invariants
  79. 79. Data over functionsHow to enforce invariants Write a validator function
  80. 80. Data over functionsHow to enforce invariants Write a validator function Use it in fns pre- and post-conditions
  81. 81. Data over functionsHow to enforce invariants Write a validator function Use it in fns pre- and post-conditions Use it in reftypes validators
  82. 82. Sequences as pipes
  83. 83. Sequences as pipesSequences as ephemeral media ofcomputation
  84. 84. Sequences as pipesSequences as ephemeral media ofcomputationEach stage of a pipeline yields its own seq
  85. 85. Sequences as pipesSequences as ephemeral media ofcomputationEach stage of a pipeline yields its own seqThe ends of the pipeline are not seqs:
  86. 86. Sequences as pipesSequences as ephemeral media ofcomputationEach stage of a pipeline yields its own seqThe ends of the pipeline are not seqs: db, network, persistent collection etc.
  87. 87. Sequences as pipesSequences as ephemeral media ofcomputationEach stage of a pipeline yields its own seqThe ends of the pipeline are not seqs: db, network, persistent collection etc.
  88. 88. Mutation patterns
  89. 89. Mutation patternsReftypes embody mutation patterns
  90. 90. Mutation patternsReftypes embody mutation patternsApplication state management:
  91. 91. Mutation patternsReftypes embody mutation patternsApplication state management: Refs, atoms and agents
  92. 92. Mutation patternsReftypes embody mutation patternsApplication state management: Refs, atoms and agentsProgram state management:
  93. 93. Mutation patternsReftypes embody mutation patternsApplication state management: Refs, atoms and agentsProgram state management: Vars
  94. 94. Mutation patternsReftypes embody mutation patternsApplication state management: Refs, atoms and agentsProgram state management: VarsExecution or dataflow management:
  95. 95. Mutation patternsReftypes embody mutation patternsApplication state management: Refs, atoms and agentsProgram state management: VarsExecution or dataflow management: Promises, delays and futures
  96. 96. How to thinkfunctionally?
  97. 97. Break your habits
  98. 98. Tie your imperative hand behind your back!
  99. 99. Tie your OO hand too!
  100. 100. FeaturesSyntaxCore Functional ProgrammingRecursion and loopsLazy seqs (creating your owns)PolymorphismTypesMacrosInteropMutation
  101. 101. FeaturesSyntaxCore Functional ProgrammingRecursion and loopsLazy seqs (creating your owns)PolymorphismTypesMacrosInteropMutation
  102. 102. FeaturesSyntaxCore Functional ProgrammingRecursion and loopsLazy seqs (creating your owns)PolymorphismTypesMacrosInteropMutation
  103. 103. FeaturesSyntaxCore Functional ProgrammingRecursion and loopsLazy seqs (creating your owns)PolymorphismTypesMacrosInteropMutation
  104. 104. FeaturesSyntaxCore Functional ProgrammingRecursion and loopsLazy seqs (creating your owns)PolymorphismTypesMacrosInteropMutation
  105. 105. FeaturesSyntaxCore Functional ProgrammingRecursion and loopsLazy seqs (creating your owns)PolymorphismTypesMacrosInteropMutation
  106. 106. FeaturesSyntaxCore Functional ProgrammingRecursion and loopsLazy seqs (creating your owns)PolymorphismTypesMacrosInteropMutation
  107. 107. FeaturesSyntaxCore Functional ProgrammingRecursion and loopsLazy seqs (creating your owns)PolymorphismTypesMacrosInteropMutation
  108. 108. Allowed subsetPure Functional Programming without recursion nor loops without lazy-seq without indices
  109. 109. Do it until it hurts! (and works)
  110. 110. Do it especially forill-suited problems!
  111. 111. Example:Conway’s game of life
  112. 112. RulesAt each step in time, the following transitions occur:• Any live cell with fewer than two live neighbours dies, as if caused by under-population.• Any live cell with two or three live neighbours lives on to the next generation.• Any live cell with more than three live neighbours dies, as if by overcrowding.• Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. (wikipedia)
  113. 113. Conway’s game of life Typical implementation is full of indices and loops(defn step "Takes a vector of vectors of 0 and 1, and returns the next iteration of the automaton." [board] (let [w (count board) h (count (first board))] (loop [i 0 j 0 new-board board] (cond (>= i w) new-board (>= j h) (recur (inc i) 0 new-board) :else (let [n (neighbours-count board i j) nb (cond (= 3 n) (assoc-in new-board [i j] 1) (not= 2 n) (assoc-in new-board [i j] 0) :else new-board)] (recur i (inc j) new-board))))))
  114. 114. Conway’s game of life Typical implementation is full of indices and loops(defn step "Takes a vector of vectors of 0 and 1, and returns the next iteration of the automaton." [board] (let [w (count board) h (count (first board))] (loop [i 0 j 0 new-board board] (cond (>= i w) new-board (>= j h) (recur (inc i) 0 new-board) :else (let [n (neighbours-count board i j) nb (cond (= 3 n) (assoc-in new-board [i j] 1) (not= 2 n) (assoc-in new-board [i j] 0) :else new-board)] (recur i (inc j) new-board))))))
  115. 115. Conway’s game of life And there’s more!(defn neighbours-count [board i j] (let [i+1 (inc i) j+1 (inc j)] (loop [cnt 0 x (dec i) y (dec j)] (cond (> x i+1) cnt (> y j+1) (recur cnt (inc x) (dec j)) (= [x y] [i j]) (recur cnt x (inc y)) :else (recur (+ cnt (get-in board [x y] 0)) x (inc y))))))
  116. 116. Conway’s game of life And there’s more!(defn neighbours-count [board i j] (let [i+1 (inc i) j+1 (inc j)] (loop [cnt 0 x (dec i) y (dec j)] (cond (> x i+1) cnt (> y j+1) (recur cnt (inc x) (dec j)) (= [x y] [i j]) (recur cnt x (inc y)) :else (recur (+ cnt (get-in board [x y] 0)) x (inc y))))))
  117. 117. Look, no indicesAt each step in time, the following transitions occur:• Any live cell with fewer than two live neighbours dies, as if caused by under-population.• Any live cell with two or three live neighbours lives on to the next generation.• Any live cell with more than three live neighbours dies, as if by overcrowding.• Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. (wikipedia)
  118. 118. Take a step back!
  119. 119. Look, no indicesAt each step in time, the following transitions occur:• Any live cell with fewer than two live neighbours dies, as if caused by under-population.• Any live cell with two or three live neighbours lives on to the next generation.• Any live cell with more than three live neighbours dies, as if by overcrowding.• Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. (wikipedia)
  120. 120. Neighbours!
  121. 121. Neighbours!Try to express the rules in code using theneighbours concept
  122. 122. Neighbours!Try to express the rules in code using theneighbours conceptDon’t worry about the implementation ofneighbours
  123. 123. Neighbours!
  124. 124. Neighbours!For each living cell or neighbour of a livingcell, compute the number of neighbours.
  125. 125. Neighbours!For each living cell or neighbour of a livingcell, compute the number of neighbours.Then apply generation rules.
  126. 126. Neighbours!
  127. 127. Neighbours!Compute all neighbours of the living cells.
  128. 128. Neighbours!Compute all neighbours of the living cells.Occurences count is neighbour count!
  129. 129. Neighbours!Compute all neighbours of the living cells.Occurences count is neighbour count!Then apply generation rules.
  130. 130. Neighbours!(defn step "Takes a set of living cells and returns the nextgeneration (as a set too)." [living-cells] (letfn [(alive [[cell cnt]] (when (or (= cnt 3) (and (= cnt 2) (living-cells cell))) cell))] (->> living-cells (mapcat neighbours) frequencies (keep alive) set)))
  131. 131. Neighbours!(defn step "Takes a set of living cells and returns the nextgeneration (as a set too)." [living-cells] (letfn [(alive [[cell cnt]] (when (or (= cnt 3) (and (= cnt 2) (living-cells cell))) cell))] (->> living-cells (mapcat neighbours) frequencies (keep alive) set)))
  132. 132. Neighbours!(defn neighbours [[x y]] (for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])] [(+ x dx) (+ y dy)]))(defn step "Takes a set of living cells and returns the nextgeneration (as a set too)." [living-cells] (letfn [(alive [[cell cnt]] (when (or (= cnt 3) (and (= cnt 2) (living-cells cell))) cell))] (->> living-cells (mapcat neighbours) frequencies (keep alive) set)))
  133. 133. Drafting code
  134. 134. Drafting codeDon’t go to the details
  135. 135. Drafting codeDon’t go to the detailsDraft high-level code you’d like to beable to write to solve the problem
  136. 136. Drafting codeDon’t go to the detailsDraft high-level code you’d like to beable to write to solve the problemTry to implement it
  137. 137. Drafting codeDon’t go to the detailsDraft high-level code you’d like to beable to write to solve the problemTry to implement itNegociate between practicality ofimplementation and draft code
  138. 138. But it really hurts...
  139. 139. But it really hurts...Ask for help
  140. 140. But it really hurts...Ask for help #clojure on IRC
  141. 141. But it really hurts...Ask for help #clojure on IRC Stackoverflow
  142. 142. But it really hurts...Ask for help #clojure on IRC Stackoverflow clojure google group
  143. 143. But it really hurts...Ask for help #clojure on IRC Stackoverflow clojure google group reach your local user group
  144. 144. But it really hurts...Ask for help #clojure on IRC Stackoverflow clojure google group reach your local user group create your local user group
  145. 145. But it really hurts...Ask for help #clojure on IRC Stackoverflow clojure google group reach your local user group create your local user group mail me christophe@cgrand.net

×