Jump to content

Erlang Programming/Functions

From Wikibooks, open books for an open world

← Expressions | guards →

Erlang Functions

[edit | edit source]

To see a function in erlang we can create the file: even_prime.erl with the following code.

-module(even_prime).                           % 1
-export([is_even_prime/1]).                    % 2
                                               % 3 
is_even_prime(2) ->                            % 4   clause 1 is simple
    true;                                      % 5
is_even_prime(N) when is_integer(N) ->         % 6   clause 2 has a guard: is_integer(N)
    false;                                     % 7
is_even_prime(Any) ->                          % 8   clause 3 is simple
    'I prefer integer inputs'.                 % 9

The function clauses are put in the order that they are checked. First is_even_prime(2) is checked for a match. If the argument matches then true is returned. This clause ends in a semicolon because the function is not finished being defined. If is_even_prime(2) fails to match then is_even_prime(N) is tried. is_even_prime(N) is checked for a match. N is a variable that matches any integer. The statement when is_integer is a guard that admits only integer types to N. The semicolon says we have more to go. The period at the end tells us that the function is finished being defined. is_even_prime(Any) matches anything of any type and returns the value 'I prefer integer inputs'. The function is now finished. This function is a total function and should cover all possible single argument inputs.

outputs:

 2> c(even_prime). 
./even_prime.erl:8: Warning: variable 'Any' is unused
{ok,even_prime}
 3> even_prime:is_even_prime(2). 
true
 4> even_prime:is_even_prime(1). 
false
 5> even_prime:is_even_prime(seven). 
'I prefer integer inputs'
==================================================================
Syntax/structure of a function: 
==================================================================
semicolon     - ends a clause
period        - ends a function 
when          - starts a guard
arrow         - separates the head from the tail of the function
function head - input part of function includes the signature and guard
function tail - output/consequence(s) part of function
signature     - the function name and argument structure/count
==================================================================
rotate_list( [H|T] ) when is_atom(H) -> T ++ [H].
                                     .
[----signature-----] [----guard----] .  
                                     .                     
[-----------function head----------] .  [--function tail--]
                           
==================================================================