Tuesday, June 12, 2007

Erlang and calling functions

In Erlang, when you want to call a function you can use various notations:


Calling a function in another process:

NewPid = spawn(modulename, functionname, [arguments]).

Now a simple test module:


test(String) ->
{ erlang:now(), String }.

This module has one function named 'test', its arity is one (one parameter), and this function
returns a tuple that contains the datetime and the 'string' passed as the parameter.

Calling 'erlang:now()':

(master@karoten)52> erlang:now().

This is some sort of UNIX timestamp (number of seconds since 1970).

Now test our module:

Compiling it, ie compiling 'test.erl' located in the current directory:

(master@karoten)52> c(test).

Calling the funcname 'test':

(master@karoten)53> test:test("test").

Here's we have used the notation 'modulename:functionname(arguments)'.
But within the module itself we could use the notation 'functionname(arguments)'...

-export([test/1, test/0]).

test(String) ->
{ erlang:now(), String }.

test() ->

Here's come what's really important to understand in Erlang, a function is defined by its name AND its arity.
So 'test/0' is NOT 'test/1'.

In our module, what the function 'test/0' do is just calling 'test/1' with a string that contains 'test'.

Erlang is a functionnal language, so the parameter of the function 'test/1' can really be what you want, from simple string to integer to complex list of tuple...

Just try this, and you'll understand :

test:test( [ complex, list, of, atoms, "and a string" ] ).

No comments: