Clojure: from ground up
R君
Agenda
• Lisp & Clojure intro (GC, FP, immutable)
• macro
• application
Clojure
Yet Another JVM Programming Language, a Lisp dialect.
(defn concat [xs ys]!
(if (empty? xs)!
ys!
(let [[h & t] xs]!
(cons h (concat t ys)))))
Lots of Irritating Stupid Parentheses
(defn concat [xs ys]!
(if (empty? xs)!
ys!
(let [[h & t] xs]!
(cons h (concat t ys)))))
LISt Processing
S-expression
http://norvig.com/lispy.html
GC
mark compact
GC
mark and sweep
http://atlas.cs.virginia.edu/~weimer/2008-415/reading/bacon-garbage.pdf
Functional Programming
• function as first-class citizen
• work by arguments and returning value
(defn make-adder [base]
(let [ref (atom base)]
(fn [delta]
(swap! ref (partial + delta)))))
Immutable
m = new HashMap();
m.put(1, “a”);
m.put(2, “b”);
m = new PersistentHashMap();
m = m.assoc(1, “a”);
m = m.assoc(2, “b”);
macro
(defmacro when [pred & body]
`(if ~pred (do ~@body) nil))
(when (> x 2)
(* x 4))
(if (> x 2)
(* x 4)
nil)
macro
(gen-from-tpl "exception {ex} at {line}")
(defmacro gen-from-tpl
[tpl-str]
(let [partitions (re-partition #"{((?:w|-)+)}" tpl-str)
string-and-symbol (map (fn [{:keys [match? result]}]
(if match?
(-> result second symbol)
result))
partitions)]
`(str ~@string-and-symbol)))
(str "exception" ex "at" line)
application
• strom
• cascalog
• compojure
application
cascalog
(?- (stdout)
(<- [?word ?count]
(sentence :> ?line)
(tokenise :< ?line :> ?word)
(c/count :> ?count)))
SELECT word, COUNT(*)
FROM words
GROUP BY word
application
compojure
(defroutes user-routes
(POST “/login" [username password] users/login)
(GET "/user/:id" [id] users/get-by-id))
(context "/user/current" []
(GET "/" [] …)
(POST "/profile" [phone location] ...)
(GET "/posts" [text] ...)))
Why Clojure
Java interop
java.lang.Math/PI => 3.141592653589793
(.exists (java.io.File. "t1.clj")) => true
(.toUpperCase "foo") => "FOO"
Q & A
Thanks

Clojure from ground up