Useful has functions that do this and more: fix or to-fix, according to 
taste. Your iffn is just the three-argument case of to-fix: (def magnify 
(to-fix pos? inc dec)). But fix and to-fix accept more or fewer arguments 
as well, so that (fix x pos? inc) is like (if (pos? x) (inc x) x), and 
(to-fix tall? shorten thin? fatten) is (fn [x] (cond (tall? x) (shorten x) 
(thin? x) (fatten x) :else x)).

Basically both of these functions look through their clause pairs and apply 
the first transform whose test matches. fix takes its "focus" argument 
immediately, while to-fix returns a lambda that performs the requested 
operation.

On Tuesday, February 19, 2013 9:53:57 PM UTC-8, James MacAulay wrote:
>
> Sometimes I find myself writing code like this:
>
> (defn magnify [n] (if (pos? n) (inc n) (dec n)))
>
> ...and I want to get rid of all those "n"s. I've looked for a macro like 
> this, but couldn't find it, so I wrote it:
>
> https://gist.github.com/jamesmacaulay/4993062
>
> Using that, I could re-write the above like this:
>
> (def magnify (iffn pos? inc dec))
>
> I can imagine a condfn macro, too:
>
> (def magnify2 (condfn pos? inc
>                       neg? dec
>                       :else identity)
>
> Has this kind of conditional function composition been explored much? I 
> couldn't find anything like it in the standard library, but maybe I wasn't 
> looking hard enough.
>
> Cheers,
> James
>

-- 
-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to