SoFunction
Updated on 2025-04-08

Some programming skills shared by Erlang

guard

Guards can be separated by commas or semicolons, and the final result is defined as the and results of each guard. If a semicolon is true, the final result is true.

Copy the codeThe code is as follows:

guard(X, Y) when not(X>Y), is_atom(X) ->
    X + Y.

Guard can filter elements in list comprehension:
Copy the codeThe code is as follows:

NewNodes  = [Node || Node <- AllNodes, not gb_sets:is_member(Node, NewQueried)],

Custom functions cannot be used in guard because guard should be guaranteed to have no side effects, but custom functions cannot guarantee this, so erlang prohibits the use of custom functions in guard.

list comprehension

list comprehension is a very useful syntax feature, it can be used to construct a new list, which can be used to map one list to another, which can filter list elements. As long as it is a list-related operation, priority is given to using list comprehension, which will greatly reduce the amount of code. Remember the syntax of list comprehension:

Copy the codeThe code is as follows:

[Expression || Generators, Guards, Generators, ...]
timer

Send a message to the process after a certain period of time:
Copy the codeThe code is as follows:

erlang:send_after(token_lifetime(), self(), renew_token),

Execute a function after a period of time:
Copy the codeThe code is as follows:

{ok, TRef} = timer:apply_interval(Interval, ?MODULE, announce, [self()]),

gb_trees/gb_set

pattern match

Pattern match has too many functions:

pattern match in case

Deciding multiple values ​​in case is much simpler than using logical operators:

Copy the codeThe code is as follows:

A = 1, B = 2,
case {A, B} of
    {_C, _C} -> true;
    {_, _} -> false
end

pattern match to check data type

Pattern match can be used to detect the type of variables, can be used to detect the return value of a function, just like assert in C/C++, can be used to detect abnormal states as early as possible:

Copy the codeThe code is as follows:

ping({_, _, _, _} = IP, Port) ->
    ok.
{ok, Ret} = call().

List operation

Add elements

There are many ways to add elements to list:

Copy the codeThe code is as follows:

[2]++[3, 4].
[2|[3,4]].

foldl/foldr

Used to traverse the list to calculate an "accumulated value".

Copy the codeThe code is as follows:

lists:foldl(fun(X, Sum) -> X + Sum end, 0, [1,2,3,4,5]).

That is, iterate over a list, pass each element to fun, and continue to pass the return value of fun to the next element.

zip

Construct a tuple one by one to correspond to the two lists as the element in the new list.

Copy the codeThe code is as follows:

lists:zip([1, 2, 3], [4, 5, 6]).
    => [{1,4},{2,5},{3,6}]

Digital division

16##FF, represents the hexadecimal number 0xFF, and the general format is scale##num, that is, num in scale.