Here’s a list of 10 consecutive numbers and the union function with its application.
(defn union [ids p q]
(let [pid (nth ids p)
qid (nth ids q)
pid->qid (fn [id] (if (= id pid) qid id))]
(map pid->qid ids)))
;; execute union three times
(union (union (union ids 2 6) 3 8) 6 3)
Think how the above three-union form would change with four or more unions. I’m pretty sure you’ve noticed the pattern – the innermost form
(union ids 2 6) is executed before its result is passed to another down and so on. It repeatedly calls
union with a list as the first input parameter (or the second element of the “union” list). When I saw the threading pattern, the thread macro
-> sprung to my mind. With it applied the calls are so much clearer. Have a look.
(union 2 6)
(union 3 8)
(union 6 3)
(union 8 5)
(union 9 8)
(union 7 4))
-> macro just “threads” (or weaves?) the
ids list through
When I learnt the thread
-> macro I was looking for use cases where it’d shine. It did in some samples, but it was just today when I experienced its beauty in a real-life example and realized its potential. I’m so glad I learnt it before and knew about it so I could apply it now!
p.s I still wonder if there’s a more idiomatic way to write the
pid->qid function in