Clojure session #01

Since I’m not posting nothing here lately, I’ve decided to write some thoughts and examples with some subject, this time is Clojure.

Multiple arities

(defn sum
"sum given numbers"
([] 0)
([x] (+ x))
([x y] (+ x y)))

Undefined number of arguments

(defn sum [& all] (reduce + all))

Local bindings

This can help you to bind some values and let your code more readable

(let [x 2] (+ x 2)) ; x only exists within let context

doing sides effects (maybe you can see this like blocks)

(do
(println "hey")
(def a (read))
(println " you typed " a))

Closures in clojure

(defn validnumber? [max] #(if (> % max) false true))
; or (defn validnumber? [max] (fn [number] (if (> number max) false true)))

(def bellow100? (validnumber? 100))

(bellow100? 9) ; true
(bellow100? 200) ; false

Curying

(def plus-one (partial + 1))
(plus-one 2)

Compose functions

(def composed (comp #(+ 2 %) +))
(composed 1 2)

Thrush operators ( -> and ->> )

-> data flow (in front) among functions
->> data flow (after) among functions

(-> 4 (- 2) (- 2))
;translates to
(- 4 2) (- 2) => (- 2 2) => 0

(->> 4 (- 2) (- 2))
;translates to
(- 2 4) (- 2) => (- 2 -2) => 4

another good usage for ->

(def person {:name "name" :age 120 :location { :country "US" } })
;instead of (:country (:location person)) a more readable way could be
(-> person :location :country)

PS: hardly based on good book Pratical Clojure

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s