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.
function:

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

Pie() ->
3.14
.
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:

-module(helloworld).
-export([area/1, either_or_both/2]).
% “_” indicates omission mode
Either_or_both(true, _) ->
True;
Either_or_both(_, true) ->
False;
Either_or_both(false, 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:
c(helloworld).

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

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:

-module(helloworld).
-export([either_or_both/2]).

Either_or_both(true, B) when is_boolean(B) ->
True;
Either_or_both(A, true) when is _boolean(A) ->
False;
Either_or_both(false, 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