Erlang Functions and Modules — Defining, Exporting, and Organizing Code
DodaTech
Updated 2026-06-29
1 min read
In this tutorial, you will learn about Erlang Functions and Modules. We cover key concepts, practical examples, and best practices to help you master this topic.
Erlang programs are organized into modules, each containing functions that can be exported to other modules. Understanding this structure is essential for writing maintainable Erlang code.
Modules
-module(math_utils).
-export([factorial/1, fibonacci/1]).
-export([area/1]). %% also exported
%% Private function
fac(0) -> 1;
fac(N) when N > 0 -> N * fac(N - 1).
%% Public wrapper
factorial(N) when N >= 0 -> fac(N).
%% Pattern matching on atoms
area({circle, R}) -> math:pi() * R * R;
area({rectangle, W, H}) -> W * H;
area({triangle, B, H}) -> B * H / 2.
%% Fibonacci
fibonacci(0) -> 0;
fibonacci(1) -> 1;
fibonacci(N) when N > 1 -> fibonacci(N-1) + fibonacci(N-2).
Function References
%% Referencing functions: fun Module:Function/Arity
lists:map(fun math_utils:factorial/1, [1, 2, 3, 4]).
%% => [1, 2, 6, 24]
%% Anonymous functions
Double = fun(X) -> X * 2 end.
Double(5). %% => 10
← Previous
Erlang Pattern Matching — The = Operator, Guards, and Function Clauses
Next →
Erlang Lists and Recursion — Tail Recursion and List Processing
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro