[erlang-questions] scope of variables
Mon Sep 4 15:04:16 CEST 2006
Vlad Dumitrescu wrote:
> True, in this case it is easy to rewrite it, but it might be much more
> difficult in the general setting, where the variable A isn't top-level
> foo() ->
> A = 2,
> ?let(X, [3, 3], begin case X of [A|B] -> B+A; _ -> -1 end).
> This is simple to rephrase, but imagine there are 10-12 of those free
> variables. It's not worth rewriting everything just to be able to use
> ?let, right? It can be done, but it's work that the compiler should
> do, not the programmer, for a language to be able to claim it has
> proper macros.
Ok, so it's not just a question of being able to use local bindings -
i's also about being able to inject code (the macro body) into some
arbitrary context and avoid accidental name capture of variables in the
macro. But then the injected code (not the context) must be written with
this in mind, or you will have to do renaming when you inject it.
If you know that the macros will not be nested, the simplest solution is
to use strange variable names in the macro bodies, for local variables
that are bound in patterns, as in:
-define(foo(X), case X of [|] -> @a; _ -> -1 end).
and you can be fairly sure that they won't capture an existing binding.
(Or just don't use patterns at all in macro bodies, for extra safety -
use explicit type tests, hd(), tl(), element(), etc., together with the
let-macro for local bindings.)
More information about the erlang-questions