On Fri, Dec 17, 2010 at 1:37 PM, Alan <a...@malloys.org> wrote:
> On Dec 17, 8:31 am, Ken Wesson <kwess...@gmail.com> wrote:
>> > 2. Is there a form for anonymous macros?
>>
>> Nope. I'm not sure why you'd want one, either.
>
> This was my reaction too, but after some thought I can imagine
> scenarios where it would be useful. For example, say I want to defn
> several versions of the same function, with slightly different
> options:
>
> (defn quiet-foo [x]
>  (magic x :quiet))
>
> (defn loud-foo [x]
>  (magic x :loud))
>
> I could write a macro to do this, then call the macro N times for my N
> functions:
> (defmacro make-foo [name opt]
>  `(defn ~name [x#]
>     (magic x# ~opt)))
> (make-foo quiet-foo :quiet)
>
> But it might be nice to have some syntax like:
> ((macro [& name-opts]
>   (doseq [[name opt] (partition 2 name-opts)]
>     `(defn ~name [x#]
>        (magic x# ~opt))))
>  [quiet-foo :quiet, loud-foo :loud])

Yeah, perhaps, though for your toy example there's more lines of code
with either macro than without any macros.

Of course you might also want to abstract out the fact that quiet and
loud get repeated in the names. Say,

(defmacro make-foo [opt]
  (let [name (symbol (str opt "-foo"))
        opt-kw (keyword (str opt))]
    `(defn ~name [x#]
       (magic x# ~opt-kw))))

user=> (macroexpand-1 '(make-foo quiet))
(clojure.core/defn
 quiet-foo
 [x__1387__auto__]
 (user/magic
  x__1387__auto__
  :quiet))

(= (defn quiet-foo [x] (magic x :quiet)))

You don't even have to stick a ' or a : before the word quiet, or ""
around it -- just (make-foo quiet)!

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

Reply via email to