Document directory
- 3.2.1 variable unchanged
- 3.2.2. Pattern Matching
- 3.2.3 why is a single assignment helpful for writing code with higher quality?
- 3.5.1 create tuples
- 3.5.2. Extract field values from tuples
- 3.6.1. Terms
- 3.6.2. definition list
- 3.6.3. Extract elements from the list
1. officially set sail
Once upon a time, a programmer accidentally read a book in a strange language. Equality is not equal, but variables cannot be changed. The syntax is so unfamiliar that it is not even object-oriented, these programs are too different ......
The alternative is not just a program, but the teaching steps of Programming are also standalone. Its authors have been teaching Concurrency, distribution, and fault tolerance endlessly, and are constantly nagging about the concept of Concurrency Oriented Programming, for concurrent programming ......
However, some programs seem very fun. That night, the programmer watched the small example of the chat program, how cute and easy to understand, it is really simple, it can't be simple, it can't use a few lines of code, file sharing and encrypted communication will jump up, so the programmer started to knock on his keyboard ......
The above passage was very simple and interesting, and brought out the features of Erlang, So that I started my Erlang journey like the programmer mentioned.
2. Install Erlang
On the official website of Erlang http://www.erlang.org/You can find its installer,
Because I am using a windows system, I directly go to the Download page and find the Windows Binary File to Download.
After the download, the installation is also very simple. Just click next. After the download is complete, you can find it in the Start Menu.
You can see this after you open it.
This is a simulator of Erlang. Of course, the same is true if you use windows cmd or bash in unix to input erl at the command prompt to start Erlang shell -- erl.
Let's try it, as shown in
Prompt 1> it indicates that this is our first command, followed by the comment text. It indicates that this line is all Erlang comments and will be ignored by the shell and Erlang compilers.
Enter 20 + 30 in the second line, and press Enter. No result is returned? In Erlang, ". + press ENTER" is used to indicate the end of a complete command,
So the third line is the prompt 1>, indicating that our first command is still not over, and then we enter ". "And press Enter. At this time, shell evaluates the expression and prints the result, 50.
Then, the prompt is programmed 2>, indicating that we started with 2nd Erlang commands.
In addition, we can use the shell Ctrl + N, Ctrl + P shortcut keys to retrieve the previously entered commands.
If the program command input is incorrect, and the system does not respond, press Ctrl + break (windows System) and you will see the following prompt:
In this case, press A to abort the current Erlang session.
3. Entry 3.1: simple integer calculation
Calculate several arithmetic expressions first
Erlang follows the standard arithmetic expression law, so 20 + 30*40 is actually 20 + (30*40) instead of (20 + 30) * 40
Erlang uses an integer of an indefinite length for arithmetic calculation, so you do not have to worry about overflow. For example:
You can also enter integers in different ways, for example:
3.2. Variables
How can I save the result of a command for later use? This is the variable, for example:
In the preceding example, we assign a value to variable X and print the value of the variable.
If you want to view the value of the variable, you can enter
With the X variable, we can also use it like this.
Algebraic Single Assignment
In junior high school, the math teacher told us that there are X in different places of the same equation, so these X points to the same thing;
But when we started learning the first programming language, we saw X = X + 1, and we were all done. This equation was obviously not true! But the teacher said we were wrong. X is not a mathematical variable, but a box ......
In Erlang, the variable restores its meaning in mathematics. When you associate a variable and value together, you are equivalent to making an asserted, it is just a statement of the facts.
However, if you want to assign a new value to X, the system will relentlessly throw you an error message:
What is this? Well, to explain it, we must break two wrong ideas:
1) X is not a variable in the traditional sense, at least not used in C/C ++/C;
2) = not a value assignment operator.
3.2.1 variable unchanged
The variable of Erlang is a single value variable, that is, the value of the variable can only be given at one time.
If a variable contains an assigned value, it is called a bound variable. Otherwise, it is a free variable.
In essence, = is a pattern matching character. When a variable is a free variable, its behavior is consistent with the value assignment.
Finally, the lexical unit defining a variable is the scope of the variable. Therefore, if a variable is used in a function statement, the value of this variable cannot jump out of the statement.
There are no global or shared private variables in different clauses of the same function. If X appears in many different functions, the values of X are also independent.
3.2.2. Pattern Matching
In most languages, = is a table value assignment statement, but in Erlang, = indicates a pattern matching operation.
Lhs = Rhs is actually such a process, evaluate the right end (Rhs), and then match the result with the left end (Lhs) pattern.
A variable, such as X, is the simplest mode. When we input X = something for the first time, Erlang will ask itself, "How can we change the value of this statement to true? ", Since X is not assigned a value, the result of something is bound to X, so that the statement is valid and the results are all happy.
However, when we enter X = anotherthing, since X is already bound to a variable, this statement will be valid only when the value of something is the same as that of anotherthing. Otherwise, an exception will be thrown. For example:
3.2.3 why is a single assignment helpful for writing code with higher quality?
The variable in Erlang is just a reference to the value. For specific implementation, a bound variable is a pointer that points to the storage zone of that value. That value cannot be changed.
Dropping "Side effects" means that our program can be parallelized.
In terms of terms, we call the memory region that can be modified a variable state. Erlang is a functional language that does not have a mutable state.
When multi-core programming comes, we will find that the benefits of adopting an immutable state are incalculable.
When a traditional language such as C or JAVA is programming for a multi-core CPU, it encounters a Memory Sharing problem. To avoid disrupting Memory sharing, it must be locked during access, it also ensures that the program will not crash when operating the shared memory. Erlang has no mutable status, no shared memory, and no locks, which are conducive to the compilation of parallel programs.
Then you will ask, if there is no variable, how can we describe the expression X = X + 1? The answer is simple. Use a new variable, such as X1, to make X1 = X + 1
(Okay... In fact, when I saw this, I sprayed a monitor ...)
3.3. Floating Point Number
Let's use floating point numbers for some operations:
Note: the last line of the first line is the integer "3", which indicates the end expression rather than the decimal point. To represent a floating point number, it should be written as "3.0"
"/" Always returns a floating point number. Therefore, "2nd" in the 4/2 expressions does not return 2, but 2.0.
Div and rem indicate integer division and remainder.
3.4. Atom
In Erlang, atoms are used to represent different non-numeric constant values.
It is similar to the macro definition of # define OP_READ 1 in C.
The atoms in Erlang are globally valid and do not require macro definition or file inclusion.
An atom is a string of characters starting with a lowercase letter followed by numbers, letters, underscores (_), or email signs,
For example, Monday, abc_d, aaa @ somehost, etc.
The characters enclosed by single quotes are also Atomic. In this form, we can make the atom start with an uppercase letter or contain non-numeric characters,
For example, '+' and 'a B C.
The value of an atom is the atom itself.
It sounds strange to discuss the number of atomic or integer values, but because Erlang is a functional language, each expression must have a value, and integers and atoms are no exception.
3.5. tuples
If you want to make up a certain number of items into a single entity, you can use tuple ).
Enclose several values separated by commas (,) in a pair of curly brackets to form a tuples.
For example, if a person named joe is 1-8 tall, the tuples can be represented as {joe, 180 }.
The tuples are similar to the structures in C. to define the point type Variable p in C, do the following:
And access a structure field through a vertex, for example:
But there is no type declaration in Erlang, so creating a point will look like this:
This statement creates a tuples and binds them to the variable P.
Different from C, there is no field name for the tuples. To facilitate memory, you can add an atom to the tuples as their first element to mark the meaning of the tuples,
Therefore, we can use {point, 10, 45} to replace the above tuples, Which is clearer.
Tuples can be nested, for example, the following example:
3.5.1 create tuples
Tuples are automatically created when you declare them. When you stop using them, the tuples are also destroyed. Erlang uses the Garbage Collector to reclaim unused memory, so we don't have to worry about memory allocation.
If the created tuples reference a bound variable, the new Meta Group will enjoy the data structure referenced by this variable. For example:
If you try to reference an undefined variable when creating a data structure, the system will give an error.
3.5.2. Extract field values from tuples
The pattern match = we mentioned earlier is used here.
Return to the example where the previous tuples represent vertices:
If you want to propose the coordinate value of a point, how can this problem be solved? As follows:
As a demonstration, we use a complex tuples:
Let's get his surname as follows:
Finally, the who
The symbol _ is called an anonymous variable. Unlike the conventional variable, the value bound to each _ does not need to be the same in different places in the same mode.
3.6 list
We use a list to store a variable number of things, such as commodities purchased in a mall, names of planets, bus sites, and so on.
Several values separated by commas are enclosed in square brackets to form a list.
The following example shows a shopping list:
Each element in the list can have different types, such
3.6.1. Terms
The first element of the List is called the head of the list, and the rest is called the tail of the list ).
The list header can be anything, but the end of the list is still a list.
The access list header is a very efficient operation. Therefore, in fact, all list processing functions start from the list header and are processed first, then process the end of the list.
3.6.2. definition list
If T is a list, [H | T] is also a list with H as the header and T as the end.
Vertical Line | the symbol can separate the header and tail of the list, while [] indicates an empty list.
Whenever we use [... | T] When constructing a list, make sure that T is a list. If T is a list, the new list will be in the "regular form", and vice versa ". Most function libraries assume that the list is regular and they cannot process the informal list correctly.
You can use [E1, E2 ,..., En | T] This form adds multiple new elements to the beginning of T, such
3.6.3. Extract elements from the list
We can use the pattern matching operation to get elements from a list. Assuming there is a non-empty list L, then the expression [X | Y] = L (X, Y are all variables) you can extract the list header to X and the end of the list to Y.
If we have a list of supermarket shopping items, the first thing we need to do is to split the list into the header and the end:
The value of this Buy1 is {oranges, 4}, and the value of ThingsToBuy2 is a list composed of the following elements.
3.7. String
Strictly speaking, Erlang does not have a string. A string is actually an integer list.
Enclose a string with double quotation marks to form a string. For example:
Note: Erlang can only use double quotation marks to represent strings, but not single quotation marks.
Here, "Hello" is just a stenographer. It actually means an integer list. Each element in the list is an integer of the corresponding character.
When shell prints a list value, it prints the list as a string only when all integers in the list are printable characters. For example:
We do not need to memorize which integer represents which character, but can use the $ symbol to represent the character's integer. For example, $ a is an integer that represents character a, and then:
Character set used in the string
The character in the string is Latin-1 (ISO-8859-1), for example, a string containing a Swedish name will be encoded.
If the expression is input in shell, you may not see the desired result. This is actually a problem of displaying the character set and region settings of the terminal. Erlang is helpless for such problems.
3.8 Reargument pattern matching
Make sure that you have mastered these
You can enter the mode = value in shell to view the running result.
The command f () will let the shell release all the variables it has bound. After using this command, all the variables become free variables.
Now we are very familiar with the basic data types and have an understanding of Single Assignment and pattern matching. Therefore, we can speed up the next chapter and learn how to define functions and modules.