can i alter a parameter within a function

Håkan Stenholm hakan.stenholm@REDACTED
Tue Aug 9 23:24:22 CEST 2005


>If I have a function which takes a parameter A as in
>the call f1("found") is it OK if I change the value of
>the parameter A within the function as below? 
>f1(A) when A /= "not_found" ->
>   VId =1,
>   if  s_key(VId) /= "not_found" ->
>          VId = VId +1,
>          f1(A),
>   true->
>        A = "not_found",
>        Vid -1
>   end
No, you can't reassign the the value of a variable in the current 
function clause scoop. The example code will result in a pattern 
mismatch (and and a runtime exception) if the true branch is ever 
selected. The initial guard ensures that A /= "not_found", so the 
pattern match (which will be done as A has already been set to a value) 
will always fail.

You'll need to introduce a new variable to hold any new value you want 
to use in a function clause. --if-- and --case-- statements are usually 
used like this:

function(...) ->
    %% Res is set / bound to the last value of the evaluated branch.
    %% Res could be [A,B,C], {A,B}, A or any other valid
    %% pattern matching pattern, but is usually a single variable or a 
tuple if several
    %% variables are to be set by the branching statement (if, case, ...)
    Res = if ... ->
        true ->
    %% do something with the new variable/s from Res

ps: atoms are faster than strings - i.e. the code will run faster if you 
use 'not_found' and 'found' instead, a single integer compare is done 
instead of a string compare.

>Start your day with Yahoo! - make it your home page 

More information about the erlang-questions mailing list