O'Reilly logo

Designing for Scalability with Erlang/OTP by Steve Vinoski, Francesco Cesarini

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 2. Introducing Erlang

This book assumes a basic knowledge of Erlang, which is best obtained through practice and by reading some of the many excellent introductory Erlang books out there (including two written for O’Reilly; see “Summing Up”). But for a quick refresher, this chapter gives you an overview of important Erlang concepts. We draw attention particularly to those aspects of Erlang you’ll need to know when you come to learn OTP.

Recursion and Pattern Matching

Recursion is the way Erlang programmers get iterative or repetitive behavior in their programs. It is also what keeps processes alive in between bursts of activity. Our first example shows how to compute the factorial of a positive number:

-module(ex1).
-export([factorial/1]).

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

We call the function factorial and indicate that it takes a single argument (factorial/1). The trailing /1 is the arity of a function, and simply refers to the number of arguments the function takes—in our example, 1.

If the argument we pass to the function is the integer 0, we match the first clause, returning 1. Any integer greater than 0 is bound to the variable N, returning the product of N and factorial(N-1). The iteration will continue until we pattern match on the function clause that serves as the base case. The base case is the clause where recursing stops. If we call factorial/1 with a negative integer, the call fails as no clauses match. But we don’t bother dealing ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required