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.
FWIW I definitely prefer the anonymous fn version from the article, for the reasons he mentions. For whatever reason I find it much harder to parse partial, comp and friends.
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:
The comp version is:
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.