Threading Macros
Below you can find two useful clojure macros which allow you to order operations in kmore intuitive way
Thread First Macro
Let's define a helper function to concatenate two strings :
(defn addStr [s1, s2](clojure.string/join "" [s1 s2]))
And now let's just try to generate very simple sitrng concatenation with our addStr function
(println (addStr (addStr (addStr"" "one ") "two ") "three" ))
and the result is
one two three
It's working but code may not be easy to read and analyze. And now first macro enter the scene Thread First Macro .
It takes first expression and the past it as a first parameter to next function. Look at example and examine the picture
(-> "one " (addStr "two ") (addStr "three") println)
And now it is easier to understand what is really happening :
- Pass "first" as a first parameter to addStr
- Pass a result of (addStr "one" "two") as a first paramater to next addStr
- Pass a result of (addStr "one two" "three") to println
exercise 1
There is a formula to calculate first n integers :
n(n+1)/2*
Which can be coded as
(defn sumn [n] (/ (* n (+ n 1)) 2))
Rewrite this code with usage Thread First Macro
exercise 1 Solution
(defn macroSumn [n] (->1
(+ n)
(* n)
(/ 2)))
Thread Last Macro
Here instead result of an expression is passed as a last parameter of a next function
So for code
(->> "three" (addStr "two ") (addStr "one ") println)
the result is the same
one two three
exercise 2
You can just sum 1...n with code
(defn sumn [n](reduce + (range 0 (+ 1 n))))
(sumn 6)
but do it with thread last macro
exercise 2 Solution
(defn sumntl [n]
(->> n
(+ 1)
(range 0)
(reduce +))
)