Erlang (programming language)/Tutorials/Functions: Difference between revisions

From Citizendium
Jump to navigation Jump to search
imported>Eric Evers
imported>Meg Taylor
m (spelling: differnt -> different)
 
(4 intermediate revisions by 2 users not shown)
Line 4: Line 4:
==Syntax of functions==
==Syntax of functions==


Functions are defined by the domain of the arguments and the number of arguemnts. A function ends with a period. A function defined over differnt domains are separated by semicolons. A fact function gives an answer that is sensitive to the domain of the input. With strings it gives a fact. With counting numbers it gives the factorial function.
Functions are defined by the domain of the arguments and the number of arguemnts. A function ends with a period. A function defined over different domains are separated by semicolons. A fact function gives an answer that is sensitive to the domain of the input. With strings it gives a fact. With counting numbers it gives the factorial function.


  fact("aloha") -> "Aloha is a greating";
  fact("aloha") -> "Aloha is a greating";
Line 12: Line 12:
  fact(N) when is_integer(N) and (N > 0) ->  
  fact(N) when is_integer(N) and (N > 0) ->  
     fact(N-1)*N;
     fact(N-1)*N;
  fact(N) when N < 0 -> error.
  fact(N) when N < 0 -> numerical_error;
fact(N) -> unknown_domain.


==Calling functions==
==Calling functions==
Line 40: Line 41:
Or we can use apply:
Or we can use apply:


  apply(lists, max, [[a, b, c]]).
  8> apply(lists, max, [ [a, b, c] ]).
c
 
We could use a lambda expression stored in a variable:
 
9> Max = fun(A)->lists:map(A) end.
10> Max([a,b,c]).
c
 
We can now use Max with map:
 
11> lists:map(Max, [ [a,b,c] ]).
  c
  c

Latest revision as of 01:14, 7 February 2010


Functions

Syntax of functions

Functions are defined by the domain of the arguments and the number of arguemnts. A function ends with a period. A function defined over different domains are separated by semicolons. A fact function gives an answer that is sensitive to the domain of the input. With strings it gives a fact. With counting numbers it gives the factorial function.

fact("aloha") -> "Aloha is a greating";
fact(String) when is_a_list(String) -> 
    "no fact is known about " ++ String;
fact(0) -> 1;
fact(N) when is_integer(N) and (N > 0) -> 
    fact(N-1)*N;
fact(N) when N < 0 -> numerical_error;
fact(N) -> unknown_domain.

Calling functions

One can use the direct syntax to call a function: Package_atom:function_atom(Args).

1> lists:max([4,5,6]).
6

We can represent the parts with variables.

3> Package = lists.
lists
4> Function = max.
max
5> Args = [4,5,6].
[4,5,6]
6> Package:Function(Args).
6

Or we can use the tuple notation:

7> {lists,max}([4,5,6]).
6

Or we can use apply:

8> apply(lists, max, [ [a, b, c] ]).
c

We could use a lambda expression stored in a variable:

9> Max = fun(A)->lists:map(A) end.
10> Max([a,b,c]).
c

We can now use Max with map:

11> lists:map(Max, [ [a,b,c] ]).
c