[erlang-questions] Reassigning variables

Ulf Wiger <>
Wed Mar 18 19:37:01 CET 2009


Matthew Dempsky wrote:
> 
> 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}),
>         ....
[...]
> But, please, show me how you would write v3_core:lc_tq/5 without
> numbered state variables without losing any readability.

So there's a pattern there, and there's actually a library
function that might help to eliminate most of the numbered
variable names.

thread(Fs, St) ->
    lists:mapfoldl(fun(F,St1) -> F(St) end, St, Fs).

lc_tq(Line, E, [{generate,Lg,P,G}|Qs0], Mc, St0) ->
   {Gs,Qs1} = splitwith(fun is_guard_test/1, Qs0),
   {[Name, Head, Tname], St1} =
      thread([fun(St) -> new_fun_name("lc", St) end,
              fun new_var/1,
              fun new_var_name/1], St0),
    ...

Whether it's more readable is perhaps a matter of
taste. It ought to be easier to maintain though.

BR,
Ulf W
-- 
Ulf Wiger
CTO, Erlang Training & Consulting Ltd
http://www.erlang-consulting.com



More information about the erlang-questions mailing list