[erlang-questions] Reassigning variables

Oscar Hellström oscar@REDACTED
Wed Mar 18 12:41:43 CET 2009


Hi,

Peter Sabaini wrote:
> On Tuesday 17 March 2009 21:21:29 mats cronqvist wrote:
>   
>> 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.
>>     
>
> 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. 
>
>   
For the logging yes, but for ?debugFmt() you should probably be looking
at something like the dbg module, or the trace bif, and avoid having
debug macros in your code completely. But if you look at intermediate
variables such as X1, X2, X3 etc, how often do you log all of them and
not just the final result?
> 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
>>     
>
>   
> ------------------------------------------------------------------------
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
Best regards

-- 
Oscar Hellström, oscar@REDACTED
Office: +44 20 7655 0337
Mobile: +44 798 45 44 773
Erlang Training and Consulting Ltd
http://www.erlang-consulting.com/




More information about the erlang-questions mailing list