Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 4, 2020 05:55 am GMT

Clojure 101 / threading macros

When you have deeply nested functions or transformations, it might help you to consider a thread macro which helps the readability of your code.

(-> x & forms)

-> is the thread-first macro. It evaluates one form and passes it as the first argument into the next form.

;; these two are equivalent(.toUpperCase (first ["chicken" "egg"]))(-> ["chicken" "egg"] first .toUpperCase);; and so are these(assoc {} :key 24)(-> {} (assoc :key 24))

(->> x & forms)

->> is the thread-last macro. It evaluates one form and passes it as the last argument into the next form.

;; these two are equivalent(apply + (map (fn [x]                (* x 2)) [1 2 3]))(->> [1 2 3]     (map (fn [x] (* x 2)))     (apply +));; and so are these(reduce +     (filter even? [1 2 3 4]))(->> [1 2 3 4]     (filter even?)     (reduce +))

Here is a dad joke in case you need a laugh:

The spool of the thread asked the needle, "How you doing?" The needle replied, "sew sew."

I'm out.

Warmly,
DH


Original Link: https://dev.to/icncsx/clojure-101-threading-macros-4898

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To