我把所有穿过的袜子在沙发上摆成一个二叉堆,每天回家便把袜子脱下来放在堆的最末尾,然后每次拿起两双袜子放在鼻子下闻闻,不断向上调整它在堆中的位置,直到比它的父亲更臭为止。这样,我每天早晨出门时便能方便地选出一双最不臭的袜子。
Clojure Practical Functional Approach on JVM Sun Ning 2011.11.28
Agenda <ul><li>Introduction to Clojure
Real World Clojure
Clojure People </li></ul>
 
Introduction to Clojure <ul><li>Functional Programming
Lisp Syntax
State Management
Macro
Java Interop </li></ul>
Introduction to Clojure <ul><li>Functional Programming
Lisp Syntax
State Management
Macro
Java Interop </li></ul>
<ul>Functional Programming </ul><ul><li>Avoiding Mutable State
Functions as First-Class Values
Lambdas and Closures
Higher-Order Functions
Side-Effect-Free Functions
Recursion
Lazy vs. Eager Evaluation
Declarative vs. Imperative Programming </li></ul>
<ul>Functional Programming </ul><ul><li>Avoiding Mutable State </li><ul><li>Better concurrency (no need for locking)
Persistent data structure </li></ul></ul>zs = xs + ys
<ul>Functional Programming </ul><ul><li>Functions as First-Class Values
Lambdas and Closures
Higher-Order Functions </li></ul>;; integer as first class value (def a 10) ;; function as first class value (def b (fn [x...
<ul>Functional Programming </ul><ul><li>Side-Effect-Free Functions </li></ul>;; function that free of side effect (defn f ...
<ul>Functional Programming </ul><ul><li>Recursion </li><ul><li>Recursive Looping </li></ul></ul>public int sumAll(int n) {...
<ul>Functional Programming </ul><ul><li>Lazy Evaluation </li></ul>;; define data (def data [1 2 3 4 5]) ;; a function with...
<ul>Functional Programming </ul><ul><li>Declarative Programming </li><ul><li>DSL </li></ul></ul>(cd &quot;/home/login&quot...
Introduction to Clojure <ul><li>Functional Programming
Lisp Syntax
State Management
Macro
Java Interop </li></ul>
Syntax <ul><li>Symbol:  user/m
Character:  a
Integer:  1 2 3
String:  “hello”
Keyword:  :world
Boolean:  true
Null:  nil </li></ul>
Collections <ul><li>Vector:  [1 2 3]
List:  (1 2 3)
Set:  #{1 2 3}
Upcoming SlideShare
Loading in …5
×

Clojure: Practical functional approach on JVM

1,975 views

Published on

Clojure introduction, concepts, functional programming elements. Real world usage. Clojure community heros.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,975
On SlideShare
0
From Embeds
0
Number of Embeds
14
Actions
Shares
0
Downloads
22
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Clojure: Practical functional approach on JVM

  1. 1. 我把所有穿过的袜子在沙发上摆成一个二叉堆,每天回家便把袜子脱下来放在堆的最末尾,然后每次拿起两双袜子放在鼻子下闻闻,不断向上调整它在堆中的位置,直到比它的父亲更臭为止。这样,我每天早晨出门时便能方便地选出一双最不臭的袜子。
  2. 2. Clojure Practical Functional Approach on JVM Sun Ning 2011.11.28
  3. 3. Agenda <ul><li>Introduction to Clojure
  4. 4. Real World Clojure
  5. 5. Clojure People </li></ul>
  6. 7. Introduction to Clojure <ul><li>Functional Programming
  7. 8. Lisp Syntax
  8. 9. State Management
  9. 10. Macro
  10. 11. Java Interop </li></ul>
  11. 12. Introduction to Clojure <ul><li>Functional Programming
  12. 13. Lisp Syntax
  13. 14. State Management
  14. 15. Macro
  15. 16. Java Interop </li></ul>
  16. 17. <ul>Functional Programming </ul><ul><li>Avoiding Mutable State
  17. 18. Functions as First-Class Values
  18. 19. Lambdas and Closures
  19. 20. Higher-Order Functions
  20. 21. Side-Effect-Free Functions
  21. 22. Recursion
  22. 23. Lazy vs. Eager Evaluation
  23. 24. Declarative vs. Imperative Programming </li></ul>
  24. 25. <ul>Functional Programming </ul><ul><li>Avoiding Mutable State </li><ul><li>Better concurrency (no need for locking)
  25. 26. Persistent data structure </li></ul></ul>zs = xs + ys
  26. 27. <ul>Functional Programming </ul><ul><li>Functions as First-Class Values
  27. 28. Lambdas and Closures
  28. 29. Higher-Order Functions </li></ul>;; integer as first class value (def a 10) ;; function as first class value (def b (fn [x] (+ x a))) ;; anonymous function #(+ a %) ;; function that generate a closure (def c (fn [x] #(+ x %))) ;; high order function (function as parameter) (def d (fn [f x] (f x a)))
  29. 30. <ul>Functional Programming </ul><ul><li>Side-Effect-Free Functions </li></ul>;; function that free of side effect (defn f [x] (+ x 1000)) ;; function with side effect (defn f [x] (println (str “logging: x=” x)) (+ x 1000)) ;; I/O operations are side effect (defn dump [writer data] (.write writer data))
  30. 31. <ul>Functional Programming </ul><ul><li>Recursion </li><ul><li>Recursive Looping </li></ul></ul>public int sumAll(int n) { int i = 1, s = 0; while(i <= n) { s = s + i; i++; } return s; } public int sumAll(int n) { if ( n > 0){ return n + sumAll(n-1); } else { return 0; } } (defn sum-all [n] (if (> n 0) (+ n (sum-all (dec n))) 0)) (defn sum-all2 [n s] (if (> n 0) ( recur (dec n) (+ n s)) s)) (defn sum-all [n] (sum-all2 n 0)) java.lang.StackOverflowError Tail recursion
  31. 32. <ul>Functional Programming </ul><ul><li>Lazy Evaluation </li></ul>;; define data (def data [1 2 3 4 5]) ;; a function with side effect (defn side-effect-inc [i] (println i) (inc i)) ;; create lazy sequence with map (def lazy-data (map side-effect-inc data)) ;; consume first 2 items for lazy sequence (take 2 lazy-data) (1 2 3 4 5 2 3) (take 5 (range)) (take 5 (repeat “a”))
  32. 33. <ul>Functional Programming </ul><ul><li>Declarative Programming </li><ul><li>DSL </li></ul></ul>(cd &quot;/home/login&quot; (path &quot;/home/login/bin&quot; (run &quot;clojure&quot;))) (cd &quot;/home/login&quot; (path &quot;/home/login/bin&quot; (env &quot;JAVA_OPTS&quot; &quot;-XMaxPermSize=128m&quot; (run &quot;ant compile&quot;))))
  33. 34. Introduction to Clojure <ul><li>Functional Programming
  34. 35. Lisp Syntax
  35. 36. State Management
  36. 37. Macro
  37. 38. Java Interop </li></ul>
  38. 39. Syntax <ul><li>Symbol: user/m
  39. 40. Character: a
  40. 41. Integer: 1 2 3
  41. 42. String: “hello”
  42. 43. Keyword: :world
  43. 44. Boolean: true
  44. 45. Null: nil </li></ul>
  45. 46. Collections <ul><li>Vector: [1 2 3]
  46. 47. List: (1 2 3)
  47. 48. Set: #{1 2 3}
  48. 49. Map: {:a 1 :b 2} </li></ul>
  49. 50. <ul><li>(def a 12)
  50. 51. (def b “tomcat”)
  51. 52. (def c (fn [x y] (+ x y)))
  52. 53. (def c #(+ %1 %2))
  53. 54. (defn c [x y] (+ x y)) </li></ul>
  54. 55. Introduction to Clojure <ul><li>Functional Programming
  55. 56. Lisp Syntax
  56. 57. State Management
  57. 58. Macro
  58. 59. Java Interop </li></ul>
  59. 60. State management <ul><li>Coordinated vs. Independent State </li><ul><li>Coordinated updates can’t just take one identity into account—they have to manage the states of several interdependent identities to ensure that they are all updated at the same time and that none are left out. </li></ul><li>Synchronous vs. Asynchronous Updates </li></ul>
  60. 61. State management <ul><li>Ref - Synchronous, Coordinated
  61. 62. Atom – Synchronous, Independent
  62. 63. Agent – Asynchronous
  63. 64. Vars – Thread local values </li></ul>
  64. 65. State management ;;refs and STM (def a (ref 0)) (def b (ref 1)) (dosync (alter a inc) (alter b + @a)) @a @b ;;atoms (def a (atom 0)) (def b (atom 1)) (swap! a inc) (swap! b + @a) @a @b ;;agents (def a (agent 0)) (def b (agent 1)) (send a inc) (send b + @a) ;;thread local binding (def a 0) (def b 1) (binding [a 100] (+ b a)) a
  65. 66. STM <ul><li>Multiple version concurrent control </li><ul><li>Each transaction gets its own view of the data that it’s interested in.
  66. 67. Each transaction merrily chugs along making changes to in-transaction values only.
  67. 68. Examine the refs against the modification target for conflicts.
  68. 69. Commit changes or Retry </li></ul></ul>
  69. 70. Introduction to Clojure <ul><li>Functional Programming
  70. 71. Lisp Syntax
  71. 72. State Management
  72. 73. Macro
  73. 74. Java Interop </li></ul>
  74. 75. Macro <ul><li>Write code that writes code </li></ul>
  75. 76. Macro (defmacro cd &quot;change current directory&quot; [path & cmd] `(str &quot;cd &quot; ~path &quot;; &quot; ~ @cmd) ) (defmacro run &quot;simply run a command&quot; [cmd] `(str ~cmd &quot;; &quot;) )
  76. 77. Macro (cd “/home/nsun” (run “rm -rf ./*”)) cd /home/nsun; rm -rf ./*; (macroexpand '(cd &quot;/home/nsum&quot; (run &quot;rm -rf ./*&quot;))) (clojure.core/str &quot;cd &quot; &quot;/home/nsum&quot; &quot;; &quot; (run &quot;rm -rf ./*&quot;))
  77. 78. Introduction to Clojure <ul><li>Functional Programming
  78. 79. Lisp Syntax
  79. 80. State Management
  80. 81. Macro
  81. 82. Java Interop </li></ul>
  82. 83. Java Interop – Java for Clojure (import java.util.Date) (def now (Date.)) (.getTime now) (System/currentTimeMillis)
  83. 84. Java Interop - Clojure->Java (ns gen-class-test.core (:gen-class :state value :init init :constructors {[String] []} :methods [[printValue [String] void] ^{:static true} [version [] String]])) (defn version [] &quot;1.0&quot;) (defn -init [name] [[] (atom {:name name})]) (defn -printValue [this prefix] (println (str prefix @(.value this))))
  84. 85. Real World Clojure where functional programming landed
  85. 86. Real World Clojure <ul><li>Network programming
  86. 87. Web development
  87. 88. Databases </li></ul>
  88. 89. Network Programming <ul><li>Aleph – network programming framework (HTTP/TCP/UDP)
  89. 90. Lamina – Abstraction of Queue
  90. 91. Gloss – Abstraction of bytes protocol
  91. 92. Based on Netty </li></ul>
  92. 93. Aleph (defcodec dummy-codec (finite-frame :int24 (string :utf8))) (defn echo-handler [ch client-info] (receive-all ch #(do (println %) (enqueue ch %)))) (start-tcp-server echo-handler {:port 1234, :frame dummy-codec}) Gloss codec Lamina queue Aleph
  93. 94. Web Development <ul><li>Web handler abstraction </li><ul><li>Ring (Similar to WSGI, Rack) </li></ul><li>Web frameworks </li><ul><li>Compojure
  94. 95. Noir </li></ul></ul>
  95. 96. Ring (defn app [req] {:status 200 :headers {&quot;Content-Type&quot; &quot;text/html&quot;} :body &quot;Hello World from Ring&quot;}) Middleware Middleware Middleware Handler Middleware
  96. 97. Compojure framework (defroutes default-routes (GET &quot;/rage/:id&quot; [] get-rage) (GET &quot;/rages/:channel&quot; [] get-rages)) (defn get-rage [req] (let [id (:id (:params req))] (json-response (get-data id)))) (defroutes default-routes (GET &quot;/rage/:id&quot; [] get-rage) (GET &quot;/rages/:channel&quot; [] get-rages))
  97. 98. Clojure JDBC DDL ;; database config (def db {:classname &quot;org.hsqldb.jdbc.JDBCDriver&quot; :subprotocol &quot;hsqldb&quot; :subname &quot;testdb&quot; :user &quot;SA&quot; :password &quot;&quot;}) (defn create-db [] (jdbc/with-connection db (jdbc/create-table table-name [:name &quot;VARCHAR(32)&quot; &quot;PRIMARY KEY&quot;] [:submitter &quot;VARCHAR(32)&quot;] [:title &quot;VARCHAR(512)&quot;])))
  98. 99. Clojure JDBC DML (jdbc/with-connection db (jdbc/with-query-results results [(str &quot;select * from &quot; (name table-name))] (into [] results)))
  99. 100. Clojure People Meet clojure hackers on github
  100. 101. @richhickey <ul><li>Creator of clojure
  101. 102. Presentations: </li><ul><li>Simple made Easy
  102. 103. Hammock-driven-development </li></ul></ul>
  103. 104. @fogus <ul><li>Clojure and ClojureScript core developers
  104. 105. Author of “The Joy of Clojure”
  105. 106. http://blog.fogus.me/ </li></ul>
  106. 107. @nathanmarz <ul><li>Leader engineer of backtype (acquired by twitter)
  107. 108. Creator of </li><ul><li>Storm (realtime computation framework)
  108. 109. Cascalog (clojure query language on hadoop) </li></ul></ul>
  109. 110. @mmcgrana <ul><li>Heroku engineer
  110. 111. Author of Ring spec
  111. 112. Author of </li><ul><li>Clj-redis
  112. 113. Clj-http
  113. 114. Clj-stacktrace
  114. 115. ... </li></ul></ul>
  115. 116. @technomancy <ul><li>Heroku engineer
  116. 117. Emacs hacker </li><ul><li>Author of emacs-starter-kit </li></ul><li>Author of leiningen (clojure build tool) </li></ul>
  117. 118. @Raynes <ul><li>17 years old Clojure guy
  118. 119. co-developer of </li><ul><li>Clojail
  119. 120. tryclj.com </li></ul><li>Clojure community and me </li></ul>
  120. 121. Many more <ul><li>@ztellman (Aleph, Lamina, Gloss)
  121. 122. @ibdknox (Noir, Korma, I Will Build Your Prototype )
  122. 123. @weavejester (Compojure, Ring)
  123. 124. @ghoseb (Planet Clojure)
  124. 125. @cemerick (O'Reilly Clojure Programming)
  125. 126. @stuarthalloway (Pragmatic Programming Clojure)
  126. 127. @stuartsierra (Clojure core developer, Apress Practical Clojure) </li></ul>
  127. 128. Q&A
  128. 129. Thanks

×