Some programming skills shared by Erlang

Time:2019-3-20

guard

Guard can be separated by commas or semicolons, which represent the final result of each guard and the final result is true as long as any guard is true.

Copy 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 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 guarantee 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 grammatical feature that can be used to construct a new list, to map one list to another, and to filter list elements. As long as the list-related operations are implemented, priority should be given to using list comprehension, which will greatly reduce the amount of code. Remember the grammar of list comprehension:

Copy codeThe code is as follows:
[Expression || Generators, Guards, Generators, …]
timer

Send a message to the process after a certain time:

Copy codeThe code is as follows:
erlang:send_after(token_lifetime(), self(), renew_token),

Execute a function after a period of time:

Copy codeThe code is as follows:
{ok, TRef} = timer:apply_interval(Interval, ?MODULE, announce, [self()]),

gb_trees/gb_set

pattern match

Pattern matching has too many functions:

pattern match in case

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

Copy 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 matching can be used to detect the type of variables and the return value of functions. Like assert in C/C++, pattern matching can be used to detect abnormal states as early as possible.

Copy codeThe code is as follows:
ping({_, _, _, _} = IP, Port) ->
    ok.
{ok, Ret} = call().

List operation

Additive elements

There are many ways to add elements to a list:

Copy codeThe code is as follows:
[2]++[3, 4].
[2|[3,4]].

foldl/foldr

Used to traverse lists to compute an “accumulative value”.

Copy codeThe code is as follows:
lists:foldl(fun(X, Sum) -> X + Sum end, 0, [1,2,3,4,5]).

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

zip

A tuple is constructed by matching two lists one by one as an element in the new list.

Copy codeThe code is as follows:
lists:zip([1, 2, 3], [4, 5, 6]).
    => [{1,4},{2,5},{3,6}]

Digit base

16\ FF, denotes the hexadecimal digit 0xFF. The general format is scale num, which is num in scale.