# Erlang Code Examples

Code examples in the ErlangLanguage.

Erlang was first implemented as a dialect of PrologLanguage, which is how it got most of its syntax (one of many exceptions being the nifty ErlangBitSyntax).

Here is a module defining a simple recursive function, illustrating simple pattern matching and guards:

``` -module(math).
-export([factorial/1]).

factorial(0) ->
1;
factorial(X) when X > 0 ->
X * factorial(X-1).

```

The BowlingGame, complete with tests. Illustrates more pattern matching, tuples such as {1,2} and lists such as [1,2,3].

Capitalised symbols are variables. Assignment to a constant (or an already bound variable, as Erlang is a SingleAssignmentLanguage) is actually a pattern match.

Matching [H|T] breaks a list into its first and remaining elements (Head and Tail).

``` -module(bowling).
-export([test/0,score/1]).
-import(lists,[duplicate/2]).

test() ->
0 = score(duplicate(10,{0,0})),
60 = score(duplicate(10,{3,3})),
21 = score([{4,6},{3,5}|duplicate(8,{0,0})]),
23 = score([{4,6},{5,3}|duplicate(8,{0,0})]),
26 = score([{10,pass},{5,3}|duplicate(8,{0,0})]),
15 = score(duplicate(9,{0,0}) ++ [{4,6},{5,nothrow}]),
18 = score(duplicate(9,{0,0}) ++ [{10,pass},{5,3}]),
ok.

score(Frame) ->
score(Frame,1,0).

score([{10,_}|T], 10, Total) ->
Total + 10 + element(1,hd(T)) + element(2,hd(T));
score([{First,Second}|T], Turn, Total) when First==10 ->
score(T, Turn+1, Total+10+element(1,hd(T))+element(2,hd(T)));
score([{First,Second}|T], Turn, Total) when First+Second==10, Turn==10 ->
Total + 10 + element(1,hd(T));
score([{First,Second}|T], Turn, Total) when First+Second==10 ->
score(T, Turn+1, Total+10+element(1,hd(T)));
score([{First,Second}|T], Turn, Total) ->
score(T, Turn+1, Total+First+Second);
score([], _Turn, Total) ->
Total.

```

An echo server. It works fine as long as you don't interrupt it. If you interrupt it, it doesn't release the socket, so there's some more work to do.

``` -module(echo).
-export([start/1,server/1,handle_messages/1]).

start(Port) ->
spawn(?MODULE,server,[Port]).

server(Port) ->
{ok, Socket} = gen_tcp:listen(Port,[{packet,line}]),
listen(Socket).

listen(Socket) ->
{ok, Active_socket} = gen_tcp:accept(Socket),
Handler = spawn(?MODULE,handle_messages,[Active_socket]),
ok = gen_tcp:controlling_process(Active_socket, Handler),
listen(Socket).

handle_messages(Socket) ->
{tcp,error,closed} ->
done;
{tcp,Socket,Data} ->
gen_tcp:send(Socket,Data),
echo:handle_messages(Socket);
_Other ->
unexpected
end.
```

EditText of this page (last edited October 25, 2007) or FindPage with title or text search