I kept using an extra line of code for this, so I decided to create the following function:
Another extra line of code can similarly be removed using this function:
Obviously, the raw forms (i.e. using doseq or map) can be far more powerful when used with more arguments. Still, these simple versions cover 99.9% of my use-cases.
I keep both these (and a few more) in a handy utils.clojure namespace I created for just such functions.
What are the differences between domap and doeach? Also, why not (doall (map function coll)) instead of using ->> macro?
Ah, I see: doeach returns nil and doesn’t retail coll head.
If you’re using clojure 1.4 I think `mapv` (now in core) would be better than your domap in most cases since it avoids the overhead of the intermediate lazyseqs and uses transients.
These definitions are a little more concise, and they don’t modify `map`’s argument list:
(def map’ (comp doall map))
(def doeach (comp dorun map))
Reblogged this on s-expressions and commented:
Cross-posted from Zolo Labs.
I’m a big fan of utility functions, because in general I’m a minimalist, an diff I can have less code then I’m going to be happy.
I noticed I tend to use them more when working on my own projects and less when working on projects with a lot of other people because I feel like there can be more effort to read utility functions.
For example, in Midje there was a very common pattern like this:
(cond x
(predicate1 x) (do something)
(predicate2 x) (do something-else)
(predicate 3 x) (do another-thing)
:else :etc))
So I wrote `pred-cond`:
(pred-cond x
predicate1 (do something)
predicate2 (do something-else)
predicate3 (do another-thing)
:else :etc))
I felt comfortable making that change because there were only two contributors to the project, so getting the team up to speed with an updated lexicon would be easy enough.
But on a project with 10-15 programmers then I start to feel differently. In general with utility functions where I feel like the benefit of it might be pretty small I try to avoid it, for fear I’ll confuse future code readers.
I might be being overly cautious, but I prefer to err on the side of being “overly readable”, rather than the side of being “overly concise”.
@bmabey: nice mapv suggestion. The only nitpick I have with mapv is that its intent isn’t as obvious. Bi t Amit could change his definition of domap to (def domap mapv), I suppose.
@one_more_minute: Keeping the arglist is a nice bonus.