Skip to content
Defining Functions
step 1/5

Reading — step 1 of 5

Learn

~1 min readFunctions and Pattern Matching

Functions are defined with multiple clauses — each pattern-matches its arguments. The first matching clause runs.

-module(main).
-export([main/1, factorial/1]).

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

main(_) ->
    io:format("~w~n", [factorial(5)]).
  • Clauses are separated by ; (semicolon)
  • The last clause ends with . (period)
  • Guards (when ...) restrict when a clause matches

This pattern matching makes Erlang functions read like specifications:

fizzbuzz(N) when N rem 15 =:= 0 -> "FizzBuzz";
fizzbuzz(N) when N rem 3 =:= 0 -> "Fizz";
fizzbuzz(N) when N rem 5 =:= 0 -> "Buzz";
fizzbuzz(N) -> integer_to_list(N).

Note =:= for exact equality (compares both value and type). == is loose. /= is not-equal.

Anonymous functions with fun ... end:

Double = fun(X) -> X * 2 end,
Double(5).            % 10

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…