On Tue, Jul 7, 2009 at 11:47 AM, Chouser <chou...@gmail.com> wrote:

>
> On Tue, Jul 7, 2009 at 8:08 AM, Roman
> Roelofsen<roman.roelof...@googlemail.com> wrote:
> > * Real-world macros *
> >
> > Correct me if I am wrong, but it seems that people often use macros
> > for lazy evaluation of parameters. In Scala, it is quite easy to
> > accomplish the same via by-name parameters. E.g.
> >
> > def maybe(lazyarg: => Unit) = if (...) lazyarg
> >
> > lazyarg will be evaluated in the if clause, not when the method
> > 'maybe' gets invoked. I know that macros in clojure are much more
> > powerful. But what are selling points in pratice? What is a unique
> > feature of clojure's macro that you don't want to miss?
>
> Lazy args are an approachable example, but probably not my
> main usage of macros.  If that's all you want, 'delay' might
> be a better option.
>
> I use macros anytime I have patterns in my code that I want
> to factor out but for which functions are insufficient.
> I know that's a bit vague, but I'm not sure how else to
> generalize it.


I would generalize that by saying you can use a macro to extract a pattern
involving language keywords, or, in the case of Clojure, special forms, that
are otherwise difficult to manipulate without passing a fn.

For example, Java doesn't have language support like C#'s using statement
for executing some block of code and deterministically cleaning up an object
at the end. You could implement that as a function (in many languages) and
call it like this:
(defn do-and-close [o f]
  (try
    (f)
    (finally (.close o))))
(let [file (FileInputStream. "todo.txt"]
  (do-and-close file
    (fn []
      (do stuff with file))))

In Clojure this was made cleaner with a simple macro,
clojure.core/with-open. Usage:
(with-open [file (FileInputStream. "todo.txt"]
  (do stuff with file))

You could write the macro yourself if it wasn't included. Programming
Clojure does a good job of explaining this, as well as when not to use
macros.

Shawn

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