[erlang-questions] Reassigning variables

David Mercer dmercer@REDACTED
Thu Mar 19 15:09:02 CET 2009


On March 19, 2009, Adam Lindberg wrote:

> BUT, there is also another thing happening here. Each transformation can
> also return one or several variables saved for later use by later
> transformation. This can also be passed around by using a dictionary or a
> key-value list.

You're on to something here...

> f() ->
>     lists:foldl(fun(F, Acc) -> ?MODULE:F(Acc) end, {St0, []}, [foo, bar,
> baz]).
> 
> foo({St, Vars}) ->
>     % Do stuff with state and vars
>     {StNew, Vars ++ [{my_saved_var, Var}]}.
> bar({St, Vars}) ->
>     ...
>     Something = proplists:get_value(my_saved_var, Vars, default)
>     ...

Shouldn't the last line in foo/1 be:

	{StNew, [{my_saved_var, Var} | Vars]}.

That would ensure that the most recent assignment is pulled out by
proplists:get_value rather than the first assignment.  Using this approach,
we wouldn't even have to keep the state separately; just store it in the
proplist as 'state':

f() ->
    lists:foldl(fun(F, Acc) -> ?MODULE:F(Acc) end, [{state, InitialState}],
        [ foo
        , bar
        , baz
        ]).

foo(Vars) ->
    OldState = proplists:get_value(state, Vars),
    % Do stuff with state and vars
    [{state, NewState}, {my_saved_var, Var} | Vars].
bar(Vars) ->
    ...
    Something = proplists:get_value(my_saved_var, Vars, default)
    ...

Cheers,

DBM




More information about the erlang-questions mailing list