[erlang-questions] Reassigning variables

Peter Sabaini <>
Tue Mar 17 22:11:51 CET 2009


On Tuesday 17 March 2009 21:21:29 mats cronqvist wrote:
> Matthew Dempsky <> writes:
> > 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).
>
>   Apologies in advance for calling you a noob.

You can call me a noob, I don't mind ;-)

>   But in my experience, all beginners start off writing code like the
> above. Whereas seasoned Erlangers produce something more like this;
>
> x() ->
>   blah_it(xyzzy(make_whee(foo()))).

IMHO intermediate values are sometimes quite useful if not necessary -- I 
often find myself needing to break up some such nested function calls just for 
a temporary ?debugFmt() or logging call -- this is a bit of a nuisance. This 
is compounded by the fact that often the punctuation needs to change too in 
such cases. 

Note I'm not advocating mutable vars, I'm fine with hand-versioning my vars, 
but it *does* add a bit of typing. 

peter.


> make_whee(X) ->
>   case whee(X) of
>     {A,B} ->  bar(A);
>     {A,B,C}-> bar(A)
>   end.
>
> blah_it(X) when is_atom(X) -> blah(X);
> blah_it(X) when is_list(X) -> blah(list_to_atom(X)).
>
>
>   I've added some stuff to your example to make it less trivial, but
>   it's basically the same.
>
>   So I think the X1 = f(X), X2 = f(X1) anti-pattern is not a weakness
>   of the language; it's Erlang's way of telling you that you should
>   use more functions.
>
>   mats

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 197 bytes
Desc: This is a digitally signed message part.
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20090317/bf515a87/attachment.bin>


More information about the erlang-questions mailing list