Functions and clauses
| Multiple clauses | |
| Name and arity | |
| Export them | |
| Anonymous functions |
Multiple clauses
A function is a set of clauses with the same name and arity. The first clause whose pattern matches the arguments runs, and the rest are skipped.
Put the specific patterns first and the general ones last, in the same order a case expression would use.
describe(0) -> "zero";
describe(N) when N > 0 -> "positive";
describe(N) -> "negative".
Name and arity
The arity is the argument count, and it is part of the function identity. describe/1 and describe/2 are two different functions that happen to share a name.
The export list uses the name and arity pair, so main/0 and main/1 would be separate exports.
-export([describe/1, area/2]).
area(W, H) -> W * H.
Export them
Only exported functions are visible outside the module. Everything else is private, which keeps the module surface small and the refactors safe.
The compiler warns about unused and unexported functions, and the warning is your cue to clean the file.
-module(shape).
-export([area/2]).
% private helper: no export needed
double(X) -> X * 2.
Anonymous functions
The fun keyword builds a function without a name. It appears inline and is the usual way to hand behavior to another function.
Lesson 21 gives funs the full lesson; here is the shape only.
1> fun(X) -> X * 2 end.
#Fun
Next: Pattern matching
Article author: Arthur Isaev