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

Reynaldo Baquerizo reynaldomic@REDACTED
Sat Nov 26 14:55:11 CET 2011


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}.

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


test() ->
    Val = case lists:keyfind(ok, 1, [{ok,23}]) of
		  {ok, MISSING} ->
		      MISSING;
		  false ->
		      3
	      end,
    {ok, Val}.



More information about the erlang-questions mailing list