CLOJURE WORKSHOP
RECURSION
(defn length ([collection] (length collection 0)) ([collection accumulator] (if (empty? collection) accumulator (recur (rest collection) (inc accumulator)))))
(loop [x 10] (when (> x 1) (println x) (recur (- x 2))))
SEQUENCE PROCESSING
(defn balance ([string] (balance 0 (seq string))) ([count [head & tail :as chars]] (if (not (empty? chars)) (case head \( (recur (inc count) tail) \) (if (zero? count) false (recur (dec count) tail)) (recur count tail)) true)))
RECURSIVE
(defn-‐match balance ([?string] (balance 0 (seq string))) ([_ [] ] true) ([?count [\( & ?tail]] (balance (inc count) tail)) ([0 [\) & _] ] false) ([?count [\) & ?tail]] (balance (dec count) tail)) ([?count [_ & ?tail]] (balance count tail)))
PATTERN MATCHING
(defn balance [string] (-‐>> string seq (map {\( inc \) dec}) (filter identity) (reductions #(%2 %1) 0) (filter neg?) empty?))
SEQUENCE PROCESSING
PROTOCOLS
(defrecord CartesianCoordinate [x y])
(defrecord PolarCoordinate [distance angle])
(defprotocol Moveable (move-‐north [self amount]) (move-‐east [self amount]))
(extend-‐type CartesianCoordinate
Moveable
(move-‐north [{x :x y :y} ammount] (CartesianCoordinate. (+ x ammount) y))
(move-‐east [{x :x y :y} ammount] (CartesianCoordinate. x (+ y ammount))))
(defrecord CenterPointRectangle [center-‐point width height])
(defrecord CornerPointRectangle [top-‐left bottom-‐right])
(extend-‐type CenterPointRectangle Moveable
(move-‐north [self ammount] (update-‐in self [:center-‐point] #(move-‐x % ammount)))
(move-‐east [self ammount] (update-‐in self [:center-‐point] #(move-‐y % ammount))))
MACROS
'(println "Hello, World")
=> (println "Hello, World")'(println "Hello, World")
(first )'(println "Hello, World")
(first )'(println "Hello, World")=> println
function-name(def )'(println "Hello, World")(first )
(list function-name "Goodbye, Cruel World")
function-name(def )'(println "Hello, World")(first )
(list function-name "Goodbye, Cruel World")=> (println "Goodbye, Cruel World")
function-name(def )
(def new-code ) (eval new-code)
(first )'(println "Hello, World")
(list function-name "Goodbye, Cruel World")
function-name(def )
(def new-code ) (eval new-code)
(first )'(println "Hello, World")
(list function-name "Goodbye, Cruel World")
prints: “Goodbye, Cruel World”
(defmacro emoify [original-code] (let [ ] (emoify (println "Hello, World"))
function-name (first )'(println "Hello, World")(list function-name "Goodbye, Cruel World")
(defmacro emoify [original-code] (let [ ] (emoify (println "Hello, World"))
function-name (first )'(println "Hello, World")(list function-name "Goodbye, Cruel World")
prints: “Goodbye, Cruel World”
FINQuestions?
Top Related