Erlang Notes – Functions

Here is the third of some notes about erlang.

Obviously this is a very cursory glance at things. It’s really just notes to help me remember things. If you’re looking for something in more detail you can take a look at the erlang reference manual.


Functions in erlang are consist of multiple clauses. Each clause is separated by a semicolon and the final clause is terminated by a dot-whitespace. For example:

utter(dog) -> "woof";
utter(cat) -> "meow";
utter(cow) -> "moo".

In the case above we have a function utter with three clauses. Each of the clauses has a head and a body.

The head

  • The head is a function name then a pattern
    in parens, such as:


  • The pattern in the head is pattern matched based on the parameters passed when the function is called. So to execute the clause with the head defined above we would write:


  • If there are multiple clauses with heads that match the call, then the first one that matches will be used.

The body

  • The body consists of a series of expressions.
  • An expression is anything that can be evaluated to produce a value
  • You can have a series of expressions, separated by commas to produce an expression sequence. The value of the expression sequence is the value of the last expression that was evaluated.

Putting it all together

So we have:

utter(dog) -> "woof";
utter(cat) -> "meow";
utter(cow) -> "moo".

Tweaking an example from the great Programming Erlang, we can do:


perimiter({square, Distance}) -> Distance * 4;
perimiter({rectangle, With, Height}) -> Width * Height * 2.

Where you can see that having multiple clauses for a function, combined with tuples allows us to implement a sort of polymorphism.

Another thing to note about functions is that functions with the same name and a different arity are completely different functions.

That is, area(Radius) is a totally different function from area(Length * Width) as far as the runtime system is concerned.

Joe Armstrong says that erlang programmers often use this feature to provide helper functions for a main function, but that makes me throw up in my mouth a little.

Leave a Comment