In article <41102A98.806@infofiend.com>, Ben Giddings
Jesse Jones wrote:
> For example, suppose you're writing a game and you have a lot of code
> that selects behavior based on percentages (75% of hits are normal
> blows, 20% are critical hits, and 5% kill your foe out-right for
> example). Even in a language as expressive as Ruby this is a bit
> awkward to write and not especially intentional. But with macros it can
> be written very cleanly:
>
> percent-case
> 0.75 case
> normal_hit
> end
>
> 0.20 case
> critical_hit
> end
>
> otherwise
> kill_foe
> end
> endI'm sorry to say it, but I think you just proved Matz' point there. I
look at that, and it doesn't look like Ruby to me.
It's not Ruby. It's a little domain specific language (DSL) tailored to
a particular problem.
Even with your
explanation, I don't understand how it works, or how to modify it.
It works by mapping by mapping the DSL to the normal Ruby syntax at
compile time. The exact details aren't really important unless you want
to create a similar macro.
Is
"case" in your code the normal ruby "case" statement? It doesn't look
like it.
No, it isn't the normal case statement. It's essentially a brand-new
statement type that may be implemented in terms of case or may not be.
On the other hand, aside for this and a few other isolated cases, I
*hate* C macros, and *hate* the C preprocessor. It means that when
you're writing .c and .h files, you're not actually writing C code,
you're writing C/C-preprocessor code, and depending on who has touched
the codebase, you never quite know what's what.
Lisp and Dylan macros are far better than C macros. They're much more
powerful and safer as well. Much of the safety is because they're
hygienic macros which essentially means that names used in calls to the
macro refer to bindings that are in the scope of the macro call, and
names within the body of the macro refer to bindings in the scope of
the macro. In other words, unlike C macros, Lisp macros are not context
dependant and macros may define new variables without worrying about
conflicts with variables declared at the macro call site.
And in languages with a conventional syntax you can arrange things so
that macros come into play only in the appropiate context. For example,
a swap macro would only be used where a function call may be used. So,
unlike C, Dylan macros aren't applied blindly.
-- Jesse
···
<bg-rubytalk@infofiend.com> wrote: