Clojure utility functions – part I

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.

7 thoughts on “Clojure utility functions – part I

  1. What are the differences between domap and doeach? Also, why not (doall (map function coll)) instead of using ->> macro?

  2. 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.

  3. 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))

  4. 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”.

  5. @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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s