r/Clojure • • May 24 '17

Readable Clojure

http://tonsky.me/blog/readable-clojure/
94 Upvotes

31 comments sorted by

View all comments

24

u/Scriptorius May 24 '17 edited May 24 '17

Some good info there, but definitely disagree on the bit about higher-order functions.

To me, the comp example is more readable because it better expresses what you're trying to do: I want to trim and then capitalize each string. Each of those is a pure transformation and the data is just flowing through them.

On the other hand, #(capitalize #(trim %)) obfuscates the intent somewhat. I have to track down the % symbol and then read outwards. Basically, this makes you think about function calls rather than thinking about the actual transformations that are happening.

Let's say you want to go through a collection of maps, grab a number at a key, and increment it. Using #() this would be:

(map #(inc (:number %)) maps)

The comp version is:

(map (comp inc :number) maps)

Of course, a lot of it is personal preference and I used to prefer the #() version. Over time though I realized it was an almost imperative way of thinking about it. Your mind is acting like a stepwise debugger, taking each value, calling function A on it, then taking the result of that and calling function B.

Using comp helps me think less about the actual function calls and think more about higher-level transformations and changes I want to do to the data.

6

u/bliow May 25 '17

In this case, #(-> % trim capitalize) seems really natural to me. You don't necessarily need comp to invert order of control.

I think I may prefer

(map #(-> % :number inc) maps)

to both of your options.

2

u/amoe_ May 25 '17

I find it useful to define comp-> for this case.

1

u/JW_00000 May 29 '17

Does this mean comp-> is equivalent to comp with the arguments reversed?