Can pattern variables be globally bound?

Thomas Johnsson thomas@REDACTED
Tue Mar 28 16:22:47 CEST 2006


This is a messy corner in Erlang...
Although same variables in patterns in function heads and case 
expressions means equality,
'equality-ness' does not propagate into  fun()'s and list 
comprehensions, instead they denote new variables with the same name:

f(X,Y) ->                    %3
    F = fun(X) -> {X,X} end, %4
    F(Y).                    %5
f2(X,L) ->                   %6
    [ X || X <- L ].         %7
...
10> c(pat).
./pat.erl:3: Warning: variable 'X' is unused
./pat.erl:4: Warning: variable 'X' shadowed in 'fun'
./pat.erl:6: Warning: variable 'X' is unused
./pat.erl:7: Warning: variable 'X' shadowed in generate
{ok,pat}
11> pat:f(3,5).
{5,5}
12> pat:f2(3,[1,2,3,4]).
[1,2,3,4]
13>

-- Thomas


Ryan Rawson wrote:

>You are correct.  Essentially when X != 0, you are trying to
>essentially say "b IFF X*10  == X".  Which is generally not true :-) 
>So you get a case clause exception.
>
>The subject line is a little misleading, since variables can only
>exist in the context of a single function "scope" - with lexical
>scoping rules of course for fun()s.
>
>"Global" variables can be accomplished with the process dictionary or
>ets or mnesia tables.  There are other techniques, like using a
>gen_server to maintain state across requests (using recursion/tail
>recusion).
>
>-ryan
>
>On 3/25/06, Roger Price <rprice@REDACTED> wrote:
>  
>
>>The following program:
>>
>>-module(test) .           %  1
>>-export([test/1]) .       %  2
>>test (X) ->               %  3
>>  case X*10               %  4
>>  of 0 -> a               %  5
>>  ;  X -> b               %  6
>>  end .                   %  7
>>
>>compiles with no warnings, and provides the following output:
>>
>>Eshell V5.4.9  (abort with ^G)
>>1> test:test(0) .
>>a
>>2> test:test(1) .
>>
>>=ERROR REPORT==== 25-Mar-2006::14:20:45 ===
>>Error in process <0.31.0> with exit value:
>>{{case_clause,10},[{test,test,1},{shell,exprs,6},{shell,eval_loop,3}]}
>>
>>My understanding of the error message is that the pattern variable X on
>>line 6 is already bound to the value 1, and therefore no match is possible
>>for value 10.  Is this correct?
>>
>>Roger
>>
>>    
>>
>
>  
>





More information about the erlang-questions mailing list