[erlang-questions] Reassigning variables
mats cronqvist
masse@REDACTED
Tue Mar 17 21:21:29 CET 2009
Matthew Dempsky <matthew@REDACTED> 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.
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()))).
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
More information about the erlang-questions
mailing list