Erlang Day 2

My experience with day two of exploring Erlang through Seven Languages in Seven Weeks.

Day 2 for Erlang takes the standard form of looking at working with collections, control structures and functions.

Control Structures

First up is control structures. In Erlang you are more likely to see a program with lots of case statements than if statements.

Here’s an example of executing code based on a variable value.

In the example, the string matched the first clause and returned the atom gold. In the following example we use underscore (_) to match anything.

In the example you can see forth returns the match all atom nothing. Note that all but the last case clause end in a semicolon.

Let’s take a look at the if statement which uses guards, a condition that must be satisfied for a match to succeed. Note: in Erlang if is a function so each case must return a value. If you want to have a catch all else you add a guard which is always true.

e.g. In the following example if X is zero an exception will occur because it doesn’t match any of the guards.

We can fix this by adding a catch all else clause.

Anonymous Functions

A nice feature of Erlang is the ability to assign functions to variables and pass them around like variables. This makes for some succinct and easy to read code.

Fun is a keyword used to define an anonymous function. We’re not saying Square is the value returned by the function we’re assigning the function to the variable Square so we can invoke a function simply by specifying the argument list. Erlang supports dynamic typing so we don’t have to worry about return types.

Lists and Higher-Order Functions

I’m quickly realising the importance of collections in functional programming. There are lots of different functions you can use to work with collections. Here are some examples of the common ones. In the following example we iterate over the values in a list using the function lists:foreach and print out each of the items in a list.

We can make the syntax cleaner to read by creating an anonymous print function and assigning it to a variable Print.

map allows you to apply a function to each value in a list to build a list of results. In the following example I use it to create a list of squared values.

Again I could rewrite this as

If you want to limit your list to values that meet a certain criteria you can use list. E.g. day we only wanted values smaller than 3.

It’s also easy to check if all values in a list satisfy the conditions.

or if at least one value satisfies the condition

An empty list returns true for an all check as all the values in the list match the condition as there are no values while the or check returns false as no values match the condition.

Some handy methods for processing things like headers and footers are takewhile and dropwhile. takewhile takes all the elements at the start of a list while a filter is met while dropwhile discards the elements at the end of a list while a filter is met.

Finally lets look at foldl and foldr which are useful for rolling up the results of a function across a list. One of the arguments serves as an accumulator, and the other represents each item. In the example below we’re going to sum up the numbers in a list.

As we did before we can make this simpler to read using an anonymous function.

The second version is so much nicer to read.

Building a List

Using a functional language requires a whole different approach to building a list than a OO language. In the following example we build a list by returning a new list with the squared list item added. We have two clauses. The first handles an empty list and is used to stop recursion. The second splits the list into it’s first element and the rest then builds a list with the first element multiplied by it self plus square_all(rest) as the rest of the list.

List Comprehensions

A list comprehension allows you to change your list into different forms allowing you to carry out multiple transformations at once.

A real life example of when we want to modify a list could be to add tax to a shopping basket of items. Here we have our basket.

We then define a list comprehension to add the tax to the price. On the left side of the || we define the tuple we wish to create with total price for item (price multiple by quantity multiplied by tax)On the right hand side we pass in a list and use pattern matching to extract the values from the tuples in our list to populate our definition.

Another example could be to produce a catalogue and a discount catalogue for special customers. In the first list comprehension we are ignoring the quantity to create a catalogue of product and prices. In the second list comprehension we’re using the catalogue and producing a discounted catalogue by dividing the price by 2.

List comprehension provide a concise and very readable syntax which I found easy to get my head around.


  • Consider a list of keyword-value tuples, such as [{erlang, "a functional language"}, {ruby, "an OO language"}]. Write a function that accepts the list and a keyword and returns the associated value for the keyword.
  • Consider a shopping list that looks like the following where total_price is quantity times price.

    [{item, quantity, price}, ...]. Write a list comprehension that builds a list of items of the form [{item, total_price}, ...],

Bonus problem

  • Write a program that reads a tic-tac-toe board presented as a list or a tuple of size nine. Return the winner (x or o) if a winner has been determined, cat if there are no more possible moves, or no_winner if no player has won yet.

Check out my code at github