[erlang-questions] module params not visible everywhere

Richard Carlsson <>
Mon Mar 12 17:09:20 CET 2007


Ulf Wiger (TN/EAB) wrote:
> Richard Carlsson wrote:
>> Variables in a record definition are not a good idea
>> (currently). Since the expressions that specify field
>> defaults will be inline expanded at the point where you
>> create a new record, they may be subject to name capture.
>> E.g., in the following case:
>>
>>      -module(foo, [X, Y]).
>>      -record(bar, {a = X, b = Y}).
>>      ...
>>      f() ->  fun (X) -> #bar{} end.
> 
> Currently, this doesn't even compile.

I think it used to, once, and then someone realized the problem
and added a check to prevent the use of free variables. Good
to know that it's working. :-)

>> the record would probably not contain what you expected 
>> (well, perhaps if you are used to programming Emacs Lisp...).
> 
> In the case of module parameters, it ought to be safe,
> since they cannot be redefined.

They can still be shadowed by locally bound variables in
fun heads and list comprehension generators, just as if
you had written:

     f(X) ->  fun (X) -> #bar{} end.

(the transformation for parameterized modules does just that - it
adds the module-global variables to each function).

>> For now, the easiest way to get this right is to write the 
>> field initializer functions manually (in any case it's best 
>> not to put anything more complicated than a function call in 
>> a record field initializer; you'll get code duplication and whatnot).
> 
> Unfortunately, this is not so easy in my particular case,
> since I'm recompiling legacy code (epp, in this particular
> case) in erlhive. The code is written, and I add special
> module parameters onto the modules to handle user context. 
> Part of the goal is to rewrite as little of the code as 
> possible.
> 
> The original record definition _did_ have only a function
> call to dict:new(). The code generator wraps this, 
> "unfortunately" adding a context based on the module 
> parameter. That has worked beautifully until now. (:
> 
> For most users, I guess your proposed workaround is 
> perfectly fine.

And for you as well: it should be a simple thing to lift all
record field initializers to new nullary functions. If you
already have a tricky parse transform going, this should be a
minor addition to it.

     /Richard




More information about the erlang-questions mailing list