0x00 says in front

ɔ ː ŋ/ ɔ ː l ə ŋ/ When I first saw it, I felt like I couldn’t pronounce it right, but when I saw Erlang’s phonetic symbols on Wikipedia, I was able to pronounce it correctly, and it wasn’t that weird. Because of my work experience with the language, I only had three days to read The book Erlang Programming. I learned the language with one goal in mind: to convert an Erlang log collection and analysis statistics code into Python. Erlang, on the other hand, avoids comments and tries to make the code clear when writing function and variable names. In this way, learning Erlang became necessary. Fortunately, the leader gave three days to learn, and three days was basically enough. In addition to this introductory article on basic syntax, there will be a follow-up article or two on concurrent programming and distributed programming, which is Erlang’s area of expertise. Without further ado, show me your article

0x01 Configuring the Development Environment

Dependency tools:

  • Erlang version: 18.3
  • IDE: IDEA

Download link:

  • Erlang: www.erlang.org/downloads select OTP18.3.
  • IDEA:www.jetbrains.com/idea/downlo… Select the Community edition.

IDEA configuration Erlang plugin:

  • IDEA official documentation – Use IDEA to develop Erlang

0x02 Basics

annotation

  • The % % symbol marks the beginning of the comment.
  • The %% symbols are usually used to comment functions.
  • The %%% three symbols are usually used to comment modules.

variable

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

Floating point Numbers

  • Floating-point numbers must contain a decimal point followed by one digit in base 10
  • When you divide two integers by a slash, the result is automatically converted to a floating point number
  • Div is rounded, rem mod

Three kinds of punctuation marks

  • The entire function definition ends with a period.
  • Function arguments, data constructs, and sequential statements are separated by commas (,)
  • Function definition,case,if,try.. catch,receivePatterns in expressions match with a semicolon (;). boundary

identity

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

Block expression

Begin is used when the syntax in a part of the program requires only a single expression, but logically requires multiple expressions. End fast expression

begin
  Expr1,
  ...
  ExprN
end
Copy the code

0x03 Built-in data structure

Tuples and pattern Matching (Deconstruction)

  • _ represents discarded variables, the same as in Python
  • The structure of the tuples on the left and right sides of the pattern match must be the same.
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
Copy the code

The list of

  • List elements can be of different types.
  • List header: The first element of a list
  • End of list: The portion of a list divided by the first element
  • A vertical bar symbol |
    • Separate the top and bottom 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 operation demo code

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

List expression

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

1> L = [1.2.3.4.5].
[1.2.3.4.5]
2> [2 * X || X <- L].
[2.4.6.8.10]
3> [X || {a, X} <- [{a, 1}, {b, 2}, {c, 3}, {a, 4}, hello, "wow"]].
[1.4]
Copy the code

string

Erlang’s string is a list of integers. The contents of the integer list consist of the ASCII code corresponding to each character

1> I = $s.
115
2> [I-32, $u, $r, $p, $r, $i, $s, $e].
"Surprise"
3> $r.                                
114
4> [I-32, $u, $r, $p, 114, $i, $s, $e].
"Surprise"
Copy the code

Mapping group (Map)

A mapping group is a python-like dictionary consisting of multiple key-vaule structures that conform to data types. Specific use is as follows

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

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 and file name)
  • Command to compile the module: c(module name). Once compiled successfully, it is loaded into the current shell
  • Module name: function name (parameter)
  • Import functions from modules:-import(lists, [map/2, sum/1]).
  • Export functions in modules:
    • Exporting the specified function-export([start/0, area/2]).
    • Export all functions-compile(export_all).To avoid adding or deleting functions to export during the development phase
-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.
Copy the code

Compile the module and call the function

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

0 x05 function

The basic function

Functions that have the same name and header (the number of arguments, arity) are the same function. So functions with the same name and different headings are two completely different functions. Different purpose functions with the same name are usually used as auxiliary functions.

  • The function does not explicitly return a value; the result of the last statement in the function is the return value of the function.

  • A semicolon (;) is used between parallel logical branches of the same function. Boundary; Sequential statements are separated by commas (,).

Example code: Evaluates the sum of list elements

-module(learn_test).
-author("ChenLiang").

%% API
-export([sum/1]).

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

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

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>
2> Double = Z.
#Fun<erl_eval.6.50752066>
3> Double(4).
8
4> TempConvert = fun({c, C}) -> {f, 32 + C * 9 / 5};
5> ({f, F}) -> {c, (F - 32) * 5 / 9}                
6> end.                                             
#Fun<erl_eval.6.50752066>
7> TempConvert({c, 100}).                           
{f,212.0}
8> TempConvert({f, 212}).
{c,100.0}
Copy the code

Higher-order functions

Functions that return fun or take fun as an argument are called higher-order functions.

A function that takes fun

Common are the map(Fun, List1) -> List2, filter(Pred, List1) -> List2 functions in the Lists module.

Use see lists module: www.erlang.org/doc/man/lis…

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]).
[2.4.6]
Copy the code

Function that returns fun

Typically, the returned function encapsulates some variables and logic. Normally you don’t write functions that return fun.

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

0 x06 assertion

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

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

0 x07 record

A record is a tuple based key-value data definition in Erlang, as shown in the following example:

-module(learn_test).
-author("ChenLiang").

%% API
-export([record_test1/0, record_test2/0]).

-record(person, {name, age=18, hobby=["erlang"]}).    %% Record definitions can be stored in HRL and ERL

record_test1(a) ->
  Person = #person{name="hahaha"},    %% assigns values to fields in record
  Person#person.hobby.    %% accesses fields in record through the. Operator

record_test2(a) ->
  Person = #person{},
  #person{name = Name} = Person,    %% Gets the Record field by pattern matching
  Name. % % output undefined
Copy the code

0x08.HRL header file

Some files have an.hrl extension. These.hrl headers are used in.erl files as follows:

-include("File_Name").
Copy the code

Such as:

-include("mess_interface.hrl").
Copy the code

HRL files can contain any legal Erlang code, but usually contain only records and macro definitions.

0x09 Case/if expression

Case expression

Case syntax

case Experssion of
  Pattern1 [when Guard1] -> Expr_seq1;
  Pattern2 [whenGuard2] -> Expr_seq2; .end
Copy the code

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 no match is found, an error is reported.

Example of the case statement:

-module(learn_test).
-author("ChenLiang").

%% API
-export([filter/2]).


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

The result is as follows in erL shell:

1> c(learn_test).
{ok,learn_test}
2> learn_test:filter(fun(X) -> X rem 2 =:= 0 end, [1, 2, 3, 4, 5]).
[2,4]
Copy the code

If expression

Example of if statement usage

-module(learn_test).
-author("ChenLiang").

%% API
-export([bigger/2]).


bigger(X, Y) ->
  if
    X > Y -> X;
    X < Y -> Y;
    true -> -1
  end.
Copy the code

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

0 x10 abnormal

Everything in Erlang is an expression and has a return value, so the exception capture statement also has a return value.

Catch all exceptions _:_

-module(learn_test).
-author("ChenLiang").

%% API
-export([catch_exc1/0,catch_exc2/0]).


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

catch_exc1(a) ->
  try
      exception()
  catch_ _ - >111
  end.

catch_exc2(a) ->
  try
    exception()
  catch_ - >222
  end.
Copy the code

Erl shell outputs the result

1> learn_test:catch_exc1().
111
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)
Copy the code

Multiple types of error detection can be performed using the try catch style.

How do I elegantly check many conditions in Erlang?


Please give me a thumbs up!

Carefully organized the computer from all directions from the entry, advanced, actual combat video courses and e-books, according to the catalog reasonable classification, always can find you need to learn information, what are still waiting for? Go to download!!

Can’t forget, there will be echoes, friends to help me like it, thank you very much.

I am a senior software engineer of YY with four years of work experience. I refuse to be a slashes programmer.

Listen to me. It’s a lot of progress

If lucky enough to be able to help you, please help me [like], give a attention, if you can along with comments to encourage, will be very grateful.

List of articles: More

All my articles, answers and copyright protection platform cooperation, copyright belongs to the workplace Liangge all, unauthorized, reproduced will investigate!