0x00 says ahead

Eg: Erlang, Opec Opec When I first saw it, I felt that I could not pronounce it correctly. Later, I saw that Erlang was marked with phonetic symbols on the wiki, so I could pronounce it correctly, and it was not so weird. My work exposure to the language gave me only three days to read the book Erlang Programming. I learned the language with one goal in mind: to convert the Erlang log collection and analysis statistics into Python code. Erlang’s style is to avoid comments and try to express the meaning of the code when writing function and variable names. This made it necessary to learn Erlang. Fortunately, the leader gave me three days to learn Erlang, which was almost enough. In addition to this primer on basic syntax, there will be an article or two on concurrent and distributed programming, which is, after all, Erlang’s area of expertise. Without further ado, show me your article

<! –more–>

0x01 Configure the development environment

Dependent tools:

  • Erlang version: 18.3

Download link:

  • Erlang:https://www.erlang.org/downloads otp18.3 can choice.
  • IDEA:https://www.jetbrains.com/ide… Select Community Edition.

Idea Configuration Erlang Plugin:

  • Official documentation for IDEA – Developing Erlang with IDEA

0x02 Basics


  • The % % symbol indicates the beginning of a comment.
  • The %% symbol is commonly used for annotation functions.
  • The %%% symbol is usually used for comment modules.


All variables must begin with an uppercase letter. Variables can be assigned only once and cannot change after assignment. The f() function releases the shell binding variable.

Floating point Numbers

  • Floating-point numbers must contain a decimal point and there must be a decimal number behind the decimal point
  • When dividing two integers by /, the result is automatically converted to a floating point number
  • DIV is rounded and REM is mod

Three kinds of punctuation marks

  • The entire function definition ends with a period.
  • Separate function arguments, data constructs, and sequential statements with commas “,”
  • Function definition,case,if,try.. catch,receiveWhen matching patterns in an expression, use the semicolon “;” boundary


The identity test symbol =:= and the inequality test symbol =/=

Block expression

Begin is used when the syntax somewhere in the program requires that only a single expression be used, but the logic requires that multiple expressions be used here… End fast expression


0x03 Built-in data structure

Tuples and pattern matching (deconstruction)

  • _ stands for discarded variables, the same as in Python
  • The pattern card = tuples on the left and right sides must have the same structure when matching.
1> Point = {Point,20,43}. {Point,20,43} 2> {Point, x, y} = Point. ** Exception error: No match of right hand side value {point,20,43} 3> {point, X, Y} = Point. {Point,20,43} 4> X.20 5> Y.43 6> Person = {Person, {name, {first, Joe}, {last, Armstrong}}, {footSize, 42}}. {person,{name,{first,joe},{last,armstrong}},{footsize,42}} 7> {_, {_, {_, Who}, {_, _}}, {_, Size}} = Person. {person,{name,{first,joe},{last,armstrong}},{footsize,42}} 8> Who. joe 9> Size. 42

The list of

  • List elements can be of different types.
  • List header: The first element of a list
  • End of a list: The rest of a list except for the first element
  • A vertical bar symbol |

    • Split the head and tail of the list
    • [E1 and E2, E4,…, | L] : using | to the list of L join multiple elements structure into a new list
  • List link operator ++ (infix add operator)

List manipulation demonstrates code

1> L = [1+7, hello, 2-2, {cost, apple, 30-20}, 3]. 
2> L1 = [123, {oranges, 4} | L].
3> [E1 | L2] = L1.
4> E1.
5> L2.
6> [E2, E3 | L3] = L2.
7> E3.

List expression

Format: [F (X) | | X < – L]

1 > L = [1, 2, 3, 4, 5]. [1, 2, 3, 4, 5] 2 > [2 * X | | X < - L]. 3 >,4,6,8,10 [2] [X | | {a, X} < - [{a, 1}, {b, 2}, {c, 3}, {a, 4}, hello, "wow"]]. [1, 4]


An Erlang string is a list of integers. The contents of the integer list are made up of an ASCII code corresponding to each character

1> I = $s.
2> [I-32, $u, $r, $p, $r, $i, $s, $e].
3> $r.                                
4> [I-32, $u, $r, $p, 114, $i, $s, $e].

Mapping group (Map)

A mapping group is a datatype conformant composed of multiple key-vaule structures, similar to a Python-like dictionary. Specific use is as follows

1> M1 = #{"name" => "alicdn", "percentage" => 80}.
#{"name" => "alicdn","percentage" => 80}
2> maps:get("name", M1).
3> M2 = maps:update("percentage", 50, M1).
#{"name" => "alicdn","percentage" => 50}
4> map_size(M1).
5> #{"name" := X, "percentage" := Y} = M2.
#{"name" => "alicdn","percentage" => 50}
6> X.
7> Y.

The symbols used to construct mapping groups and pattern matching are different, the difference between => and :=. See the use of the Erlang Maps library for a common PUT method.

0 x04 module

  • A module is stored in an.erl file (with the same module name as the file name)
  • Command to compile the module: c(module name). Once compiled successfully, it is loaded into the current shell
  • Call a function in a module: Module name: Function name (parameter)
  • Functions in the import module:-import(lists, [map/2, sum/1]).
  • Functions in the export module:

    • Exporting the specified function-export([start/0, area/2]).
    • Exporting all functions-compile(export_all).To avoid adding or removing functions from export, which is common during development
-module(learn_test). -author("ChenLiang"). %% API -export([area/1]). area({rectangle, Width, Height}) -> Width * Height; Area ({circle, R}) -> 3.14159 * R * R; area({square, X}) -> X * X.

Compile the module and call the function

1> c(learn_test). {ok,learn_test} 2> learn_test:area({circle, 2.0}).12.56636 3>

0 x05 function

The basic function

A function with the same name (number of arguments, arity) is the same function. So a function with the same name and different purpose is a completely different function. Functions with different purposes of the same name are often used as auxiliary functions.

  • The function does not return a value explicitly. The result of the last statement executed in the function is the return value of the function.
  • The semicolon “; “is used between parallel logical branches of a function. Boundary; Sequential statements are separated by a comma “, “.

Sample code: Calculates the sum of list elements


%% API

sum(L) -> sum(L, 0).

sum([], N) -> N;
sum([H|T], N) -> sum(T, H + N).

Anonymous functions

The anonymous function in Erlang is fun. Fun can also have several different words.

1> Z = fun(X) -> 2*X end. # fun <erl_eval.6.50752066> Double = Z. # fun <erl_eval.6.50752066 Double(4).8 4> TempConvert = fun({c, C}) -> {f, 32 + C * 9 / 5}; 5 > {f, f} - > {c, 5/9 (f - 32) *} 6 > end. # Fun < erl_eval. 6.50752066 > > 7 TempConvert ({c, 100}).} {f, 212.0 8 > TempConvert ({212} f,). {c, 100.0}

Higher-order functions

A function that returns fun or takes fun as an argument is called a higher-order function.

Function that takes fun as an argument

Common is the map(Fun, List1) -> List2, filter(Pred, List1) -> List2 function in the lists module.

Use see lists module: https://www.erlang.org/doc/ma…

1> Even = fun(X) -> X rem 2 =:= 0 end. # fun <erl_eval.6.50752066 2> lists:map(Even, [1, 2, 3, 4, 5]) 6]). [false, true, false, true, false, true] 3 > lists: filter (Even, [1, 2, 3, 4, 5, 6]), minus [2]

Function that returns fun

Typically, some variables and logic are encapsulated inside the returned function. Normally, we don’t write a function that returns fun.

1> Mult = fun(Times) -> (fun(X) -> X * Times end). # fun <erl_eval.6.50752066> 2> Triple = Mult(3). # Fun < erl_eval. 6.50752066 > 3 > Triple (4). 12

0 x06 assertion

Enhance the function of pattern matching, and add some ability of variable testing and comparison to pattern matching

max(X, Y) when X > Y -> X;
max(_, Y) -> Y.

0 x07 record

A record is a tuple based key-value data definition in Erlang, used as follows:

-module(learn_test). -author("ChenLiang"). %% API -export([record_test1/0, record_test2/0]). -record(person, {name, Age =18, hobby=[" Erlang "]}). Record_test1 () -> Person = # Person {name="hahaha"}, Person# Person.hobby. %% passes for the field in Record. Record_test2 () -> Person = # Person {}, # Person {name = name} = Person, Retrieving the record field Name through pattern matching. %% output undefined

0x08.hrl header file

Some files have an extension of.hrl. These.hrl header files are used in.erl files and are used as follows:


Such as:


The.hrl file can contain any legitimate Erlang code, but it usually contains only records and macro definitions.

0x09 case/if expression

Case expression

Case statement syntax

case Experssion of Pattern1 [when Guard1] -> Expr_seq1; Pattern2 [when Guard2] -> Expr_seq2; . end

The result of Expression is matched with each Pattern one by one. If the match is successful, the value of the Expression sequence is calculated and returned. If all matches fail, an error is reported directly.

Examples of using case statements:


%% API

filter(P, [H|T]) ->
  case P(H) of
    true -> [H|filter(P, T)];
    false -> filter(P, T)
filter(_, []) -> [].

The results of running in ERL shell are as follows:

1> c(learn_test).
2> learn_test:filter(fun(X) -> X rem 2 =:= 0 end, [1, 2, 3, 4, 5]).

If expression

The if statement uses the example


%% API

bigger(X, Y) ->
    X > Y -> X;
    X < Y -> Y;
    true -> -1

If there is no matching assertion, an exception is thrown. So the last assertion is usually the true assertion.

0 x10 abnormal

Everything in Erlang is an expression and has a return value, so does the exception-catching statement.

Catch all exceptions _:_


%% API

exception() ->
  exit({system, "123123"}).

catch_exc1() ->
      _:_  -> 111

catch_exc2() ->
    _  -> 222

The ERL shell outputs the result

1> learn_test:catch_exc1().
2> learn_test:catch_exc2().
** exception exit: {system,"123123"}
     in function  learn_test:exception/0 (learn_test.erl, line 17)
     in call from learn_test:catch_exc2/0 (learn_test.erl, line 28)

Multiple error detection can be performed using the Try Catch style.

StackOverflow -How do I elegantly check many conditions in Erlang?

Remember to help me thumb up oh!

Carefully organized the computer in all directions from the entry, advanced, actual video courses and e-books, according to the catalog reasonable classification, always can find the learning materials you need, what are you waiting for? Go and pay attention to download!!

Never forget for a moment, there will be echoes, friends help me to point a like it, thank you very much.

I am a senior software engineer in YY, with four years of working experience. I refuse to be a slash programmer who contended to be the leader of the company.

Listen to me, more progress, program life is a shuttle

If you have the honor to help you, please help me to click “like”, give a attention, if you can give a comment to encourage, will be very grateful.

List of workplace articles: More articles

All my articles and answers have cooperation with the copyright protection platform. The copyright belongs to the workplace Liang Ge. Without authorization, reprint will be investigated!