[erlang-questions] Reassigning variables

Robert Raschke rtrlists@REDACTED
Wed Mar 18 10:18:11 CET 2009


On Tue, Mar 17, 2009 at 6:02 PM, Matthew Dempsky <matthew@REDACTED> wrote:
> I like pattern matching in the majority of cases, but I find I write
> enough code where I need to incrementally update a data structure, and
> maintaining that code is a pain when I have code like:
>
>  X = foo(),
>  X1 = bar(X),
>  X2 = xyzzy(X1),
>  blah(X2).
>
> and later want to change it to:
>
>  X = foo(),
>  X1 = whee(X),
>  X2 = bar(X1),
>  X3 = xyzzy(X2),
>  blah(X3).
>
> This means having to change four lines of code, when really it's
> conceptually just one change.  I'd like to suggest being able to do
> something like:
>
>  X = foo(),
>  r(X) = whee(X),
>  r(X) = bar(X),
>  r(X) = xyzzy(X),
>  blah(X).
>
> where "r(?VAR) = ?EXPR" means to reassign ?VAR to ?EXPR, even if it
> previously has an assigned value.
>
> Thoughts?  Does anyone have suggestions for better syntax?  I think
> this can be handled with a parse transform, and I'm considering
> writing a parse transform to handle it.  (I haven't checked if anyone
> else has proposed similar functionality in the past, but this is
> something that's been bugging me for a while, and I've finally had to
> rename variables manually enough times to propose this.)

Usually, this kind of "problem" comes about not because of the
sequence you write above. I find much more common is something along
the lines of

{value X} = foo(),
{ok, X1} = bar(X),
{ok, X2} = xyzzy(X1),
blah(X2).

I haven't read the whole of this long thread, so maybe some ideas
cover this kind of sequence.

But I have to admit, that I find code like that extremely lazy.
Potentially excusable for a throw away program, but even then ...

It is soooo much better to give intermediate results proper names.
That way you might actually spot potential reuse of values in
subsequent code expansion. Never mind noticing potential misuse of
values, which using generic X or X1 won't help you with.

Robby



More information about the erlang-questions mailing list