Read erlang.org above Erlang course four-day tutorial
1. Number type, two points to note
1) B#val represents the number Val stored in B-binary, such as
7> 2#101.
5
101 of binary storage is 10 binary 5.
2) $Char The ASCII encoding that represents char, for example, $ A = 65
2. More difficult to translate the concept of--atom, can be understood as a constant, it can contain any character, start with a lowercase letter, if not start with a lowercase letter or a symbol other than the letter, need to be included in single quotation marks, such as ABC, ' AB '
3. Another concept,--tuple, translates into tuples, which can be understood as fixed-length arrays, is one of the fundamental data structures of Erlang:
8> {1,2,3,4,5}.
{1,2,3,4,5}
9> {a,b,c,1,2}.
{a,b,c,1,2}
10> size ({1,2,3,a,b,c}).
6
Built-in function size for length, tuples can be nested tuples or other structures. The list below is also the same.
4. Another basic data structure is a list of all languages (lists), within the [], separated, can dynamically change the size,
[123, XYZ]
[123, Def, ABC]
[{person, ' Joe ', ' Armstrong '},
{person, ' Robert ', ' virding '},
{person, ' Mike ', ' Williams '}
]
You can use the built-in function length to find the list size. The ASCII letters contained in "" represent a list of the ASCII values of these letters, such as "ABC" for the list [97,98,99].
5. These two data structures can be combined into a variety of complex structures, with the Lisp cons, List evolution of various structures like the wonderful, Erlang can also be used as the language of the Operation list.
The 6.Erlang variable has two features:
1) The variable must start with an uppercase letter or an underscore, and can contain letters, underscores, and @
2) variables can only be bound once, that is, the so-called single assignment. Or, in general, it can only be assigned once, in fact Erlang does not have the concept of assignment, the = number is also used to verify the match.
7. Pattern matching--pattern Matching,erlang's pattern matching is very powerful, see BUAAWHL 's "Erlang Syntax Summary" Introduction, the function of pattern matching is not only in the course of the data structure introduced in the disassembly, The allocation of the program also plays an important role, or the flow of control of Erlang is achieved through pattern matching. For specific functions, refer to the link to give an example of the Disassembly list in the book:
[a,b| C] = [1,2,3,4,5,6,7]
Succeeds-binds A = 1, B = 2,
C = [3,4,5,6,7]
[h| T] = [1,2,3,4]
Succeeds-binds H = 1, T = [2,3,4]
[h| T] = [ABC]
Succeeds-binds H = abc, T = []
[h| T] = []
Fails
More examples of pattern matching are given below, with a module for calculating lists, etc.
The definition of a function in 8.Erlang must be within a module (module), and the names of the modules and functions must be atom, the parameters of the function can be any Erlang type or data structure, the function to be called to export from the module, the function call form similar:
Modulename:funcname (Arg1,arg2,...).
Write our first Erlang program, a man who sees the love of Hello World:
-module (HelloWorld).
-export ([RUN/1]).
Run (Name)
Io:format ("Hello World ~w~n", [Name]).
Save As Helloworld.erl and execute in Erlang Shell:
2> C (HelloWorld).
{Ok,helloworld}
3> Helloworld:run (Dennis).
Hello World Dennis
Ok
Printed out, now explain the construction of the program,
-module (HelloWorld).
This line declares the module HelloWorld, the function must be defined within the module, and the module name must be the same as the source filename.
-export ([RUN/1]).
And this line declares the exported function, RUN/1 refers to the run function with one argument, because Erlang allows you to define multiple functions with different parameters with the same name, specifying/explaining which function to export.
The next step is the function definition:
Run (Name)
Io:format ("Hello World ~w~n", [Name]).
Uppercase starts with the variable name, calling the IO module's Format method output, ~w can be understood as placeholders, will be replaced by the actual name, ~n is a newline. Notice that the function is defined with a period. End. Then execute C (helloWorld). Compile the source code, execute:
Helloworld:run (Dennis);
9. Built-in common functions:
Date ()
Time ()
Length ([1,2,3,4,5])
Size ({a,b,c})
Atom_to_list (An_atom)
List_to_tuple ([1,2,3,4])
Integer_to_list (2234)
Tuple_to_list ({})
HD ([1,2,3,4])% Output 1, which is the head of the list, like the Lisp car
TL ([1,2,3,4])% output [2,3,4], which is the list of tail, like the CDR
10. Common Shell commands:
1) H (). Used to print the last 20 history commands
2) b (). To view all bound variables
3) f (). Cancels (forgets) all the bound variables.
4) F (Val). Cancels the specified binding variable
5) E (n). Execute nth History command
6) E (-1). Executes the previous shell command
11. Another concept that does not know how to translate--guard. Translated into constraints? Oh. Used to limit the type and range of variables, such as:
Number (x)-X is numeric
Integer (x)-X is an integer
Float (x)-X is a floating-point number
Atom (x)-X is an atom
Tuple (x)-X is a tuple
List (x)-X is a listing
Length (X) = = 3-x is a 3-length list
Size (X) = = 2-x is a tuple of length 2
X > Y + z-x >y+z
X = = Y-x is equal to Y
X =:= y-x all equals Y
(example: 1 = = 1.0 success
1 =:= 1.0 failure)
For ease of comparison, Erlang prescribes the following comparison order:
Number < Atom < reference < port < pid < tuple < list
Where PID is the ID of the process.
12. Forget to introduce the Apply function, this function is familiar to the JavaScript people, it is very kind, JavaScript implementation mixin rely on it, it is called the following way:
Apply (Mod, Func, Args), three parameters are modules, functions, and parameter lists, such as calling our first Erlang program:
Apply (Helloworld,run,[dennis]).
13.if and Case statements, the structure of the IF statement is as follows:
If
Guard1
Sequence1;
Guard2
Sequence2;
...
End
The case statement is structured as follows:
Case Expr of
PATTERN1 [When Guard1], Seq1;
Pattern2 [When Guard2], SEQ2;
PATTERNN [When Guardn], seqn
End
If and case statements have a problem, that is, when there is no pattern matching or grard is false, it can cause error, this problem case could add a similar to the default in Java:
Case Fn of
_,
True
End
By _ means arbitrary expr, which returns true, and if can:
If
True-
True
End
The same truth. Another problem to be aware of in the case statement is the scope of the variable, and the variables defined in each case branch are exported by default to the case statement, which can be referenced after the case statement ends, so a rule is that each case branch defines a variable that should be consistent or illegal, The compiler will give you a warning, such as:
F (X)
Case g (X) of
True-A = h (X), B = a + 7;
False, B = 6
End
H (A).
If a true branch is performed, both the variable A and variable B are defined, and if the false branch is executed, only the variable b is defined, and after the case statement is executed, H (a) invokes the variable A, which is unsafe because the variable a is completely undefined and the compiler gives a warning
Variable ' A ' unsafe in ' case ' (line 10)
14. Give some examples of slightly more complex model matching, such as to calculate the value of a list of numbers, averages, lengths, find out if an element is in the list, we define the module as list:
-module (list).
-export ([AVERAGE/1,SUM/1,LEN/1,DOUBLE/1,MEMBER/2]).
Average (x)->sum (x)/len (x).
SUM ([h| T]) when number (H)->h+sum (t);
SUM ([])->0.
Len ([_| T])->1+len (t);
Len ([])->0.
Double ([h| T]), [2*h|double (t)];
Double ([]), [].
Member (H, [H|_]), true;
Member (H, [_| T]), member (H, T);
Member (_, []), false.
Carefully realized, the use of recursive return to achieve, more interesting, which in fact with the use of Lisp in the return of the implementation of the iteration is the same reason, [h| T] is similar to the car and CDR operation in Lisp. _ is used to refer to arbitrary variables, when we only focus on variables here, but do not care about the value of the variable when used. Use semicolons to illustrate that the same function definition, just a different branch of definition, is determined by pattern matching to call which function defines the branch.
Another example, calculating the area of a variety of graphs, is also an example given in the course:
-module (Mathstuff).
-export ([FACTORIAL/1,AREA/1]).
Factorial (0)->1;
Factorial (N) when N>0->n*factorial (N-1).
% calculates the square area, the first matching square of the parameter tuple
Area ({square, Side})
Side * Side;
% calculates the area of the circle, matches the circle
Area ({circle, Radius})
% almost:-)
3 * radius * RADIUS;
% calculates the area of the triangle, using the Helen formula, matching triangle
Area ({triangle, A, B, C})
S = (A + B + C)/2,
Math:sqrt (s* (s-a) * (s-b) * (s-c));
% Other
Area (Other)
{invalid_object, other}.
Take a look at:
1> C (mathstuff).
{Ok,mathstuff}
2> Mathstuff:area ({square,2}).
4
3> Mathstuff:area ({circle,2}).
12
4> Mathstuff:area ({triangle,2,3,4}).
2.90474
5> Mathstuff:area ({other,2,3,4}).
{invalid_object,{other,2,3,4}}
Erlang uses% to start a single line comment.
From:http://www.blogjava.net/killme2008/archive/2007/06/13/123860.html
Introduction to Erlang (i)