[erlang-questions] Use of unsafe variables...

Raimo Niskanen raimo+erlang-questions@REDACTED
Mon Nov 28 15:37:27 CET 2011


On Sat, Nov 26, 2011 at 08:55:11AM -0500, Reynaldo Baquerizo wrote:
> Hi Antoine,
> 
> > Is this correct or documented ?
> > Thanks
> > 
> > Take this module:
> > 
> > -module(tsm_case).
> > -export([test/0]).
> > 
> > test() ->
> >    case lists:keyfind(ok, 1, []) of
> >        {ok,[_]} ->
> >           ok;
> >        false ->
> >           MISSING = 3
> >    end,
> >    {ok, MISSING}.
> > 
> > Compile it:
> > 31> c(tsm_case).
> > ./tsm_case.erl:12: variable 'MISSING' unsafe in 'case' (line 6)
> > error
> 
> An excerpt from
> http://www.erlang.org/doc/reference_manual/expressions.html
> 
> """
> The scope for a variable is its function clause. Variables bound in a
> branch of an if, case, or receive expression must be bound in all
> branches to have a value outside the expression, otherwise they will be
> regarded as 'unsafe' outside the expression.
> """
>  
> > Now see the difference:
> > 
> > -module(tsm_case).
> > -export([test/0]).
> > 
> > test() ->
> >   case lists:keyfind(ok, 1, []) of
> >     {ok,[MISSING]} ->
> >       ok;
> >     false ->
> >       MISSING = 3
> >   end,
> >   {ok, MISSING}.

So, yes it is correct and documented. The variable MISSING is bound
in all clauses of the case and hence can be used after the case.

> 
> the correct form would be to bound MISSING to the return value of the
> case expression (everything is an expression in Erlang)

The code below is by most percieved as much easier to read but the code above
is also correct. That MISSING is bound in the clause match makes it maybe
harder to grasp but it is anyway bound.

> 
> 
> test() ->
>     Val = case lists:keyfind(ok, 1, [{ok,23}]) of
> 		  {ok, MISSING} ->
> 		      MISSING;
> 		  false ->
> 		      3
> 	      end,
>     {ok, Val}.
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions

-- 

/ Raimo Niskanen, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list