Skip to content

Simple Macro Followup

June 17, 2010

Nguyen (sorry wordpress stuffed up your name) offered up a simplified version of the cond macro. Behold:

(defmacro condd [pred & clauses]
  `(letfn [(predd# [test-expr# expr#]
                   (->> test-expr# ~pred))]
          (condp predd# nil
                 ~@clauses)))

If we macro expand it:

(macroexpand-1 '(condd is-two?
                       1 (print "was one")
                       2 (print "was two")))

We get (after cleaning it up):

(letfn [(predd [test-expr expr]
               (->> test-expr is-two?))]
       (condp predd nil
              1 (print "was one")
              2 (print "was two")))

Which is pretty much the same like writing the following:

(condp (fn [expr _] (->> expr is-two?)) nil
       1 (print "was one")
       2 (print "was two"))

So it seems than condp can be bent to our will by passing nil as the expression then ignoring it in the predicate function. Thanks Nguyen.

Advertisements

From → Clojure

Leave a Comment

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

%d bloggers like this: