Erlang Study Notes

Source: Internet
Author: User
Tags integer division printable characters

Exit interaction mode: Ctrl + C and then press a; halt ().
The command must be followed by a break '.' to be valid.
% Comment out the current code to the end of the line
Compile ERL code C (modulename)

_ Represents any variable
A variable can be assigned only once in its context (scope ).

For help: Use Erl-man XX in bash

File start format:
-Module (modulename ).
-Export ([funcname1/paranum,...]).

A Data Type in Erlang, which starts with a lowercase letter. It is just a simple name, and nothing else
Tuples {}
List [] [first, second | rest] = [1, 2, 3, 4, 5] ==> first => 1 second => 2 rest => [3, 4, 5, 6]

-> Guard,-> execute this part when the previous conditions are met
If and case are followed by semicolons, and the last one is followed by an end without punctuation. A semicolon is also required at the end of the exit function of the recursive function.
If
Xxx->
...;
True->
...
End.

Case XX
Xxx->
...;
_->
...
End.

Receive
Xxx->
XXXXX;
YYY->
Yyyyy
End.

Receive
Xxx->
XXXXX,
YYY->
Yyyyy
After 5000-> % Ms
Timeout Codes
End.

The list module provides foreach (func, [XX, XX ..]) Functions and map (func, [XX, XX ..]) functions (returns a list ).

The output of a function is the output of the last thing in it.

Io: In format ~ P and ~ W outputs data in the same way, but it can divide a long row of data into several rows to make all the data visible. It also detects printable characters in the list and Outputs Data in strings.

Built-in function BIFs
Trunc (100.5) removes Decimals
Num rem 5 calculates the remainder of Num divided by 5
Atom_to_list
List_to_atom
Integer_to_list
Spawn
Whereis (mess_client) returns undefined or other values

Parallel Programming
Spawn (module, exported function, parameter list) creates a new process
Register (some_atom, Pid) gives the process a name some_atom
Pid | RegisterName! Message: send a Message to the process.
Self () returns the ID of the currently running process, including its node information.

Distributed programming
Erl-sname my_name the erlang system started with the same ip address domain (multiple erlang Systems started on the same machine)
Erl-name ip @ my_name start the erlang system in different ip Domains
Spawn (nodename, modulename, funcname, paramslist) starts a process from another node
Node () returns the name of the current node.
{Resigtername, nodename} | PID! The message sends a message to the registername process of the nodename node (the PID is the ID of the Process returned by self () or spawn (), which contains the node information, so the node name is no longer required)
Spawn_link (node, Mod, func, argS)
Monitor_node (node, flag) if the flag is true, this function enables the process called (this function) to monitor the node. If the node has been discarded or does not exist, the called process will receive a message from {nodedown, node. If flag is false, monitoring will be disabled
Disconnect_node (nodename) is disconnected from node nodename

List operations
Lists: keymember (name, 2, user_list)
Lists: keysearch (from, 1, user_list)
Lists: keydelete (from, 1, user_list)

Process
Exit (normal). exit normally
Exit (reson). Abnormal exit
Link (Other_Pid ). establishes a bidirectional connection between processes. if one of the processes that establish a link unexpectedly exits, other processes may also EXIT. If you do not EXIT, capture the {'exit ', FromPID, Reason} message for processing.

File structure
-Record (name_of_record, {field_name1, field_name2, field_name3,...}). record, in the. hrl File
-Record (message_to, {to_name, message}). equivalent to {message_to, To_Name, Message}
# Message_to {message = "hello", to_name = fred) records will be created {message_to, fred, "hello "}
-Define (name, realname). Macro, in the. hrl File
? MODULE System macro, current Module name
-Include ("xx. hrl"). At the beginning of the. erl file,. hrl is the header file of erlang.

OTP
Component (Application): Mnesia database development Debuger debugging standard library STDLIB

HELP
Macros are defined in the hrl header file. The erl file cannot be used after the include header file.

Messy records
Erlang comparison Operators
Op Description
= Equal
/= Not equal
= <Less than or equal
<Less
> = Greater than or equal
> Greater
=: = Exact equals
= // = Exact not equal
The difference between equals and exact equals:

To compare two numbers, if they are of different types, such as float and int, The = operation first converts the two numbers to the same type. Example:

1> 1 = 1.0.
True
2> 1 =: = 1.0.
False

Therefore, we recommend that you use exact equals to decomparison.

Comparison operator size level:

Number <atom <reference <fun <port <pid <tuple <list <bit string

3> 1>.

False
Op Description Argument type
+ Number
-Number
+ Number
-Number
* Number
/Floating point division. The result is the floating point number.
Bnot mona1 not operator integer
Div integer division. The result is an integer.
Rem calculates Yushu integer
Band and integer
Bor or integer
Bxor xor exclusive or integer Operation
Bsl left shift operation integer
Bsr right shift operation integer

Logical operators
Op Description
Not mona1 logic not
And logic and
Or logic or
Xor logic xor
Atomic true and false indicate logical "true" and "false"

In addition, the logical operators include orelse and andalso

The original or and operations do not contain short-circuit operations, while orelse and andalso operations do not.

Example of short circuit operation

Express1 and Express2

Express1 andalso Express2

If Express1 is false, and will continue to judge Express2, then the overall determination is false, and andalso "Short Circuit" operation, directly determine the entire expression is false, in terms of efficiency, andalso will be higher

1. A function is composed of clauses separated by semicolons. The last clause ends with a full stop, indicating that the function ends. Each clause has a function header and function body. The function header consists of the function name and the subsequent mode enclosed in parentheses. The function body consists of a series of expressions (expressions are separated by commas. When calling, if the pattern in the function header matches the call parameter successfully, the corresponding expression will be computed. The pattern is matched according to their order in the function definition. After a clause is matched, it is no longer matched.
2. The module can be compiled in the shell using the c (Module name) method. The method for calling the function in the module is: Module name: function (parameter ).
3. When a function call cannot match, a runtime error is thrown.
4. How to switch the current directory:
(1) In erlang shell: cd ("relative directory name or absolute directory name"). pwd () will return the current directory.
(2) Write a file named. erlang under the erlang installation directory. The erl shell will execute this file before the startup. The file content is as follows:
Io: format ("consulting. erlang in ~ P ~ N ", [element (2, file: get_cwd ()]). % element (2, tuples) takes the 2nd elements of the tuples. File: get_cwd () Get the current directory name
C: cd ("c:/work"). % c: Indicates executing a command in shell.
Io: format ("Now in :~ P ~ N ", [element (2, file: get_cwd ()]). % shows the current directory after switching.
5. punctuation in erlang:
Comma (,) is used to separate parameters in function calls, data constructors, and modes.
Periods (.) (followed by a blank sign, otherwise it may be the decimal point of a floating point) are used to separate the complete functions and expressions in shell.
Semicolons (;) are used to separate clauses. When clauses are used, they can be defined as piecewise functions, case statements, if statements, try... catch statements, and receive expressions.
Whenever we see a group followed by expressions, we will use semicolons to separate them.
6. The function is the number of parameters it has. Different objective functions with the same name are two completely different functions, except that their names happen to be the same. Different objective functions with the same name can be used as auxiliary functions.

7. Fun is an anonymous function. Z = fun (x)-> 2 * x end. Here Z is equivalent to the pointer of this anonymous function. This pointer can be paid to another variable, such as: Double = Z. To call this function, you can double (4 )..
8. Like normal functions, fun can have multiple parameters or clauses. You only need to add an end at the end .. The fun function of multiple clauses only writes fun in the first sub-name. The fun function of the following clause is omitted, and the last clause does not write a semicolon (;), for example:
Fun (x, y)-> X * Y;
(A, Y)->
End.
9. The fun function can be passed as a parameter to other functions (including the fun function itself) or return values of the function. A function that uses the fun function as a parameter or returns the fun function is called a higher-order function.
10. lists: map (F, L) returns a list, applying each element of list L to function F. Lists: filter (P, L) returns a list. The elements in the list are a set of elements in list L that meet the condition that P (l) is true. Lists: member (X, L) determines whether X is in list L.
11. Example of returning fun:
Fruit = [apple, pear, orange].
MakeTest = fun (L)-> (fun (X)-> lists: member (X, L) end. % note that there is no end after the previous end.
IsFruit = MakeTest (Fruit ).
IsFruit (pear). % returns true
IsFruit (dog). % returns false
Lists: filter (IsFruit, [dog, pear, apple, click]). % Returns [pear, apple]
12. The function that returns fun is a bit like the function model in c ++. It can be used to construct many versions of functions.

13. Custom for loop structure:
For (Max, Max, F)-> [F (Max)];
For (I, Max, F)-> [F (I) | for (I + 1, Max)].
14. -Import (lists, [MAP/2, sum/1]. import the MAP/2 and sum/1 functions in the lists module, so that you can directly write map (...) and sum (...).
15.-Export ([Total/1]). Export the total/1 function in this module so that total can be called outside this module.

16. List parsing: [F (x) | x <-L]. Example:
[2 * x | x <-L] % add element * 2 of list l to generate a new list.
[{Name, 2 * number} | {Name, number} <-buy]
[Shop: cost (a) * B | {a, B} <-buy]
Map (F, L)-> [F (x) | x <-L].
17. Common List parsing formats: [x | qualifier1, qualifier2,...]
X is an arbitrary expression. Each qualifier can be a generator or a filter.
Generator: Pattern <-listexpr, listexpr must be an expression to evaluate the list items.
Filter: it can be a function that returns true or false, or a Boolean expression.
In fact, the pattern of the generator can also act as a filter, for example:
[X | {a, X} <-[{a, 1}, {B, 2}, {c, 3}, {a, 4}, hello, "wow"]. % return value: [1, 4]
Equivalent to [X | {A, X} <-[{a, 1}, {B, 2}, {c, 3}, {a, 4}, hello, "wow"], A =: = a].
Map18. A ++ B: attaches List B to list A to generate A new list, but the efficiency is not high.
The A--B is to remove all elements from list A that are the same as the elements in list B. If element X appears K times in List B, K elements X are deleted sequentially from list.

19. lists: seq (M, N) returns a list of integers from M to N, including M and N. Seq should be short for sequence.

20. arithmetic expressions
1 + X
1-X
2 X * Y
2 X/Y
2 bnot x bitwise inversion of X
2 x Div Y x division y
2 x rem y x remove y to obtain the remainder
2 X band y
3 x + y
3 X-Y
3 x Bor Y: bitwise OR
3 x bxor Y: bitwise XOR of X and Y
3 x BSL n to X shifts left n places by bit
3 x BSR n to X shift n places right by bit
21. assertion (guard) is a structure used to enhance the pattern matching function.
22. when the function-defined header uses assertions, it must start with the keyword "when. For example:
Max (X, Y) when X> Y-> X;
Man (X, Y)-> Y.
23. you can use assertions wherever expressions are allowed. When an asserted is used for an expression, it either returns atomic true (considered to be successful) or atomic false (evaluation failed ).
24. assertion sequence:
A group of assertion expressions separated by commas (,) indicates the and relationship, that is, if the assertion is true, the entire assertion sequence is true.
A group of assertion expressions separated by semicolons indicate the or relationship.
25. Not all valid erlang expressions can be used as assertion expressions. Only the following expressions can be used:
Atomic true: Why do we need true assertions? This is because it can be used as catchall in the if expression, which is equivalent to the else in the if control in the C language, or the default in the switch.
Other constants (conditions or variable binding) are evaluated as false in the asserted expression.
Asserted predicates in Table 3-2 or BIF (built-in function) in Table 3-3)
Comparison expression
Arithmetic expression
Boolean expression
Short-circuit boolean expressions oralso and andalso (a bit like |||,&operation, first evaluate the value of the previous expression, if necessary, then evaluate the value of the next expression)
26. asserted predicates:
Is_atom (X)
Is_binary (X)
Is_constant (X)
Is_float (X)
Is_function (X)
Is_function (X, N)
Is_integer (X)
Is_list (X)
Is_number (X)
Is_pid (X)
Is_port (X)
Is_reference (X)
Is_tuple (X)
Is_record (X, Tag)
Is_record (X, Tag, N)
27. asserted BIF
Absolute Value of abs (X) X
Nth element of element (N, X) tuples X
Float (X) converts the number N to a floating point number
Hd (X) List X Header
Length (X) List X length
Node () current node
Node (X) process X node
Round (X) converts the number X to an integer (rounded up)
Self () identifier of the current process
Size (X) X, which is a tuples or binary data.
Trunc (X) converts the number X to an integer (truncated)
End of tl (X) List X

28. Record: a method that maps a name to the elements in the tuples one by one.
29. Record definition:
-Record (Name, {key1 = Default1, key2 = Default2, key3 ,...}). % Where Name is the record Name, Default1 and Default2 are the default values of key1 and key2 respectively.
The Record Name and key name must be atomic.
30. Records are generally stored in the erlang source code file or. hrl file, which can be referenced by other erlang source code.
31. The reference record command rr ("filename. htl"). rr in shell is the abbreviation of read record.
Release records using command rf (Record Name ).
32. Create a record: X = # todo {} creates a record. The key value of the record is the default value. Keys without default values will be paid as atomic undefined by default.
X1 = # todo {status = urgent, text = "Fix errata in book "}
33. copy record: X2 = X1 # todo {status = done }.
34. Extract the value of the record field (two methods ):
# Todo {who = W, text = Txt} = X2. % pattern matching
X2 # todo. text.
35. Record pattern matching as a function parameter:
Clear_status (# todo {status = s, WHO = w} = R)-> % s and W match the status of the record respectively, while r matches the whole record.
R # todo {status = finished} % Note: Here R is not modified, but a new record is generated and returned. The new record copies the R and changes the status to finished.
If you want to match a record of the specified type, you can use the assertion method.
Clear_status (# todo {status = s, WHO = w} = r) When is_record (R, Todo)-> r # todo {status = finished }.
36. After the record is released, the variable originally recorded will become a common tuples. It seems that the record is just a display interface of tuples.

37. If it is inconvenient to define an independent function clause for everything, use the case or if expression.
38. Case expression:
Case expression
Pattern1 [When guard1]-> expr_seq1;
Pattern2 [When guard2]-> expr_seq2;
... % The Last One cannot be added
End
Calculate the Expression value first, and then match the value with Pattern1/Pattern2.... If no match exists, an exception is thrown.
Example: filter (P, L)
Filter (P, [H | T])->
Case P (H)
True-> [H | filter (P, T)];
False-> filter (P, T)
End;
Filter (P, [])-> [].
39. if expression:
If
Guard1-> Expr_seq1;
Guard2-> Expr_seq2;
... % The Last One cannot be added
End
Generally, the last assertion of the if expression is atomic true. Otherwise, if the assertion is false, an exception is thrown.

40. Try to operate on the header of a List and avoid using code such as List ++ [H] unless the List is short. A list is usually created in a natural order. The rules are as follows:
(1) always add elements to the list header.
(2) extract elements from the header of an input list and add them to the header of an output list. The results in the output list are in the opposite order of the input list.
(3) If the order is crucial, call the list of highly optimized functions: reverse/1. (This function is implemented in the erlang Virtual Machine and has been greatly optimized ).
(4) avoid violating these principles.

41. How to return more than one list outside the function? Returns a tuple consisting of multiple lists.
42. Accumulators
Odds_and_evens_acc (L)-> odds_and_evens_acc (L, [], []);
Odds_and_evens_acc ([H | T], Odds, Evens)->
Case H rem 2
0-> odds_and_evens_acc (T, [H | Odds], Evens );
1-> odds_and_evens_acc (T, Odds, [H | Evens)
End;
Odds_and_evens_acc ([], Odds, Evens)-> {lists: reverse (Odds), lists: reverse (Evens )}.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.