You don't need a macro for this:
user> (defn conditionalize [pred then else]
(fn [& args] (if (apply pred args)
(apply then args)
(apply else args))))
#'user/conditionalize
user> ((conditionalize pos? inc dec) 3)
4
user> ((conditionalize pos? inc dec) -3)
-4
user> (def magnify (conditionalize pos? inc dec))
#'user/magnify
user> (magnify 3)
4
On Tue, Feb 19, 2013 at 9:53 PM, James MacAulay <[email protected]> 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 [email protected]
> Note that posts from new members are moderated - please be patient with your
> first post.
> To unsubscribe from this group, send email to
> [email protected]
> 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 [email protected].
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
--
Ben Wolfson
"Human kind has used its intelligence to vary the flavour of drinks,
which may be sweet, aromatic, fermented or spirit-based. ... Family
and social life also offer numerous other occasions to consume drinks
for pleasure." [Larousse, "Drink" entry]
--
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
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 [email protected].
For more options, visit https://groups.google.com/groups/opt_out.