[erlang-questions] Newbie question about Erlang style

Håkan Stenholm hokan.stenholm@REDACTED
Wed Feb 27 22:57:53 CET 2008


Kevin Scaldeferri wrote:
> On Feb 27, 2008, at 12:04 PM, Convey Christian J NPRI wrote:
>
>   
>> Is there any non-aesthetic reason prefer one of the following  
>> approaches over the other?
>>
>>
>> if Foo  -> X = 1;
>>   true -> X = 2
>> end
>>
>> vs.
>>
>> X = if
>>   Foo  -> 1;
>>   true -> 2
>>   end
>>     
>
>
>
> A related question: are all variables function scoped in Erlang?   
> Obviously, the first example wouldn't work at all if the branches of  
> an if or case created a new scope.  Is there any way to explicitly  
> create a new scope?
>   

Variables are usually defined from the point where they are introduced 
until the end of the function - so they are essentially defined in the 
entire function as one can't declare a variable without binding a value 
to it.

One exception is list comprehensions where one can shadow previously 
defined variables.

It is also possible to introduce the same variable in different branches 
of a if/case which works as expected, but may raise compiler complaints 
if one tries to use them in code outside, following the if/case - which 
requires the variable/s to be defined in all branches (even ones that 
always call exit/throw/error ...), to ensure that there is always a 
value bound to the variable.

I think it's possible to declare funs that have input variables, with 
the same names as existing ones, which shadow the previous variablenames 
- this is probably a bad idea because one might want to use those 
variables inside the fun and because the complier will (probably) create 
warnings about it.

>
> -kevin
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
>   



More information about the erlang-questions mailing list