Since the last few posts I’ve moved on from Haskell and am now looking at Erlang, another functional language developed by Ericsson and released as open source in 1998. I’ll start by giving and explaining the code for a simple “Hello World!” program.

1
2
3
4
5
-module(hello).
-export([hello/0]).

hello() ->
    io:format("Hello World!\n").

This is a basic “Hello World!” program, don’t miss the full stops, they’re very important. The first line defines the module that is provided in this file. The file and module name must be the same, so this would go in the file hello.erl. On the next line, the functions that this module provides are given, in this case a single function called hello which takes 0 arguments.

Next the hello function is declared, the code which makes up the function follows the arrow ->. This calls the function format, from the module io, which takes a string and outputs it to the terminal.

To run this code, we need to start erlang in a terminal, compile and load the hello module and call the hello function from within it. This should go as follows:

1
2
3
4
5
6
7
8
9
10
11
$ erl
Erlang R13B03 (erts-5.7.4) [source] [64-bit] [smp:2:2]
[rq:2] [async-threads:0] [hipe] [kernel-poll:false]

EShell V5.7.4 (abort with ^G)
1> c(hello).
{ok,hello}
2> hello:hello().
Hello World!
ok
3>

The Erlang shell is started from the command line by running erl, then we call the compiler with the built-in function (BIF) c with the argument hello, which compiles the module and loads the compiled code for use. Assuming this is successfull, the function returns a tuple consisting of two elements. The first is ok, which means that the action was successful and the second is the name of the compiled module. This tuple value is printed to the terminal before the shell returns to a prompt.

Finally we call the hello function from the module hello with no arguments, which prints the line “Hello World!” to the screen followed by a newline. This function returns the value ok which is then printed before the shell returns to the prompt.

NOTE: Exiting the Shell

Getting out of the Erlang shell is slightly more complicated than you might expect. Unlike most shells where a simple Ctrl-D will signal the end of input and get you out of there, you must press Ctrl-C to cause a break in the Erlang virtual machine and then press “a” and return to tell it you want to abort execution and quit the program.