[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: macros vs. blocks



Trevor Blackwell wrote:
> The toy version of the code would look like (sorry, this involves some
> obscure parts of Perl syntax...):
>
> for my $fn in (qw(table trow td ...)) {  # for each HTML operator
>     &{$HTML::{$fn}} = sub {         # define function $fn in the HTML
package
>         my($content)=@_;
>         print "<$fn>";              # The binding of $fn makes each
closure different
>         &{$content}();              # like (call content)
>         print "</$fn>";
>     };
> }

Aha!  An interesting point about this is the dynamic definition of a
function in a package.  More static languages (Scheme being one) don't
necessarily allow you to do this dynamically (although some implementations
do).  There are performance reasons for this, and compiler considerations,
which of course would be fairly foreign to most scripting languages.

So, in a case like this, once again, a macro might be used to overcome a
language limitation, without sacrificing performance, since all the
generated definitions would be known at compile time, and so can be
maximally optimized; also, startup time for the application would be
improved.

But that wasn't the reason I was thinking of macros in this case.  Your toy
example doesn't do what I imagined based on your original comment, about
generating functions from a DTD.

What I had in mind would be a program whose job would be to translate an
arbitrary DTD-like definition, i.e. more complex than the above, into
functions which implement that DTD in some way.  You could write ordinary
non-macro code to do this, but macros can be of use in a number of ways,
ranging from simply normalizing the input a bit, to actually doing major
transformations of the input purely via macro.  I wouldn't do the latter
just for the sake of it, but given a powerful macro system, it can be one of
the more concise & efficient ways to do it.  Noel's 'match' example might
give some idea about this sort of thing.

> So it's all in how you look at the problem. If you see it as
> defining a bunch of textually similar functions, you think
> macros. If you see it as a general "wrap-in-tag" function
> parameterized by what the function is, you think closures.
>
> Perhaps this dichotomy of viewpoint is big enough to warrant
> language features to appease both kinds of thinkers.

I think most users of macros in Lisp/Scheme are perfectly comfortable
thinking in closures, too.  I don't think it's so much a matter of "kinds of
thinkers" - I see it as being about having more than just one tool
available, and choosing the one most appropriate to the requirements.  (I'm
doing my best to avoid mentioning hammers and nails... oops!!)

Anton