[erlang-questions] Reassigning variables

Matthew Dempsky matthew@REDACTED
Wed Mar 18 18:33:25 CET 2009

On Wed, Mar 18, 2009 at 5:02 AM, Christian <chsu79@REDACTED> wrote:
> Rather than
> X1 = binary_to_list(Bin),
> X2 = lists:reverse(X1)
> do
> String = binary_to_list(Bin),
> RevString = lists:reverse(String),

Here's an actual block of code from the Erlang compiler:

    lc_tq(Line, E, [{generate,Lg,P,G}|Qs0], Mc, St0) ->
        {Gs,Qs1} =  splitwith(fun is_guard_test/1, Qs0),
        {Name,St1} = new_fun_name("lc", St0),
        {Head,St2} = new_var(St1),
        {Tname,St3} = new_var_name(St2),
        LA = lineno_anno(Line, St2),
        LAnno = #a{anno=LA},
        Tail = #c_var{anno=LA,name=Tname},
        {Arg,St4} = new_var(St3),
        {Nc,[],St5} = expr({call,Lg,{atom,Lg,Name},[{var,Lg,Tname}]}, St4),
        {Guardc,St6} = lc_guard_tests(Gs, St5),     %These are always flat!
        {Lc,Lps,St7} = lc_tq(Line, E, Qs1, Nc, St6),
        {Pc,St8} = list_gen_pattern(P, Line, St7),
        {Gc,Gps,St9} = safe(G, St8),                %Will be a
function argument!
        Fc = function_clause([Arg], LA, {Name,1}),

What would you suggest renaming the St0 through St9 variables to?
("St" is short for "State".)  Would you think it easier to read and
maintain this code:

    lc_tq(Line, E, [{generate,Lg,P,G}|Qs0], Mc, InitialState) ->
        {Gs,Qs1} =  splitwith(fun is_guard_test/1, Qs0),
        {Name,StateAfterNewFunName} = new_fun_name("lc", InitialState),
        {Head,StateAfterFirstNewVar} = new_var(StateAfterNewFunName),
        {Tname,StateAfterNewVarName} = new_var_name(StateAfterFirstNewVar),
        LA = lineno_anno(Line, StateAfterNewVarName),

Because I think the current code is much easier to read.  There's no
value to keeping around old state variables, and it just introduces
the possibility of bugs if you add a new line of code somewhere and
forget to renumber all of the later lines.

But, please, show me how you would write v3_core:lc_tq/5 without
numbered state variables without losing any readability.

More information about the erlang-questions mailing list