Department of Information Technology

Erlang Checkpoint

Simple Functions

Remember that Erlang uses the concept of pattern matching.

  • 1. Create the file fact.erl as follows.


     fac(0) -> 1;
     fac(N) when N > 0 -> N * fac(N-1).

  • 2. Compile the file in an Erlang shell (execute the command "c(fact)." ) and then call it for different values. Remember that you call the function by executing this command "fact:fac(9)." .

Lists and List Comprehension

Below is an implementation of a Quicksort algorithm.

     %% quicksort:qsort(List)
     %% Sort a list of items

     qsort([]) -> [];
     qsort([Pivot|Rest]) ->
         qsort([ X || X <- Rest, X < Pivot]) ++ [Pivot] ++ qsort([ Y || Y <- Rest, Y >= Pivot]).

The above example recursively invokes the function qsort until nothing remains to be sorted. The expression [ X || X <- Rest, X < Pivot] means "Choose all X where X is a member of Rest and X is less than Pivot", resulting in a very easy way of handling lists.

Concurrency and Distribution Oriented Language

Process communication is done via a share-nothing asynchronous message-passing system: every process has a "mailbox", a queue of messages sent by other processes, that are not yet consumed. A process uses the receive primitive to retrieve messages that match desired patterns. A message-handling routine tests messages in turn against each pattern, until one of them matches. When the message is consumed (removed from the mailbox) the process resumes execution. A message may comprise any Erlang structure, including primitives (integers, floats, characters, atoms), tuples, lists, and functions.

Code examples:

% execute function Func from module Mod as new process with arguments Args
 Pid = spawn(Mod, Func, Args)       
% execute function Func from module Mod in remote node Node with arguments Args
 Pid = spawn(Node, Mod, Func, Args) 

 Pid ! a_message      % send message to the process (asynchronously)

 receive       % receive message sent to this process
   a_message -> do_something;
   {data, Data_content} -> do_something_else(); % This is a tuple of a type atom and some data
   {hello, Text} -> io:format("Got hello message: ~s", [Text]);
   {goodbye, Text} -> io:format("Got goodbye message: ~s", [Text])

Updated  2008-02-12 11:33:07 by Noomene Ben Henda.