Erlang basics – functions, clauses, clause protection

The content of this title is much simpler. Just look at the use case and still use the helloworld.erl module as an example.

%% This is a simple Erlang module
% Test …
-export([pie/0, print/1]).

Pie() ->
Print(Msg) ->
Io:format(“The Message is ~p.~n”,[Msg]) %~p means to print the Erlang item in a landscaping manner, ~n means insert a newline, ~w means print Erlang string
Function clause:

-export([area/1, either_or_both/2]).
% “_” indicates omission mode
Either_or_both(true, _) ->
Either_or_both(_, true) ->
Either_or_both(false, false) ->

Area({a, X, Y}) ->
Io:format(“a, X, Y: ~p, ~p, ~p.~n”, [a, X, Y]);
Area({b, X, Y}) ->
Io:format(“b, X, Y: ~p, ~p, ~p.~n”, [b, X, Y]).

% compilation:

%call function:
1> helloworld:area({a, 500, 500}).
a, X, Y: a, 500, 500.

Note: The clause is separated by a good and the last clause is terminated by a period. All clauses of the consent function must have the same function name and the same number of arguments, and must be defined in the same place. It is not allowed to insert other function definitions between the two clauses of the same function.

For the either_or_both function, if the argument passed is or_or_both(true, 42), it is obviously true, it will only return true calmly, so this requires our protection.

Clause protection:


Either_or_both(true, B) when is_boolean(B) ->
Either_or_both(A, true) when is _boolean(A) ->
Either_or_both(false, false) ->
The clause protection begins with the keyword when and ends with the -> symbol. Can be used in the protection of the operation is very limited, most of the operators can be used (+, -, *, /, ++, etc.), some built-in functions can also be used, such as: self (), is_boolean (. ..), is_integer(…), is_atom(…), etc., but you can’t call a custom function or a function in another module.

Leave a Comment