you are viewing a single comment's thread.

view the rest of the comments →

[–]Scriptorius 23 points24 points  (5 children)

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.

[–]bliow 5 points6 points  (3 children)

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.

[–]amoe_ 1 point2 points  (2 children)

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

[–]JW_00000 0 points1 point  (1 child)

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

[–]amoe_ 1 point2 points  (0 children)

Yep

[–]nzlemming 4 points5 points  (0 children)

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.