First, Erlang syntax: variables, pattern matching
--------------------------------------
1.ELR Command: Toolbar Toolbar:start ().
2.% ... Comments
3. Capitalize the variable first letter, single assignment
4. Pattern matching
5. Atom: Hello, ' an atom with '
6. Tuple tuples: tuple nested {person,{a,1},{b,2}}
Extract the tuple field value point = {point, ten, +} {point, X, Y} = Point
7 list: definition list ThingsToBuy1 = [{oranges,4}, {newspaper,1}|{ Thingstobuy}]
Extracting elements [buy1| THINGSTOBUY2] = ThingsToBuy1.
8. String: "Hello"
9.Q () exit
10.F () Release variable
Erlang Syntax: Functions (Function-oriented programming: functions can be used as parameters, or as return values, can use list parsing, assertions, case/if, binary, bit, binary, ASCII)
--------------------------------------
1. Functions
Compiling: C (geometry)
Run: Geometry:area ({rectangle, 10, 5}).
2. anonymous function: Double = Fun (X), 2*x end.
Double (2).
Hypot = Fun (X, Y)-math:sqrt (x*x+y*y) end.
Tempconvert = Fun ({c,c}), {F, 32+C*9/5};
({f,f}), {C, (F-32) *5/9}
End.
3.fun as function parameter
Map: Lists:map (Double, [1,2,3,4]).
returns [2,4,6,8].
Filter: Lists:filter (even, [1,2,3,4]).
even = Fun (x)--(x REM 2) =:= 0 end.
4. Functions that return fun
Fruit = [Apple,pear,orange].
Maketest = Fun (L), (Fun (X), Lists:member (x,l) end) end.
Isfruit = Maketest (Fruit).
That is: Isfruit = Fun (X), Lists:member (X,[apple,pear,orange]) end.
5. Cycle
for (Max,max,f), [F (Max)];
for (I,max,f), [F (I) |for (i+1,max,f)]
6. List resolution
[2*x | | X <-L].
Definition: Buy = [{oranges,4},{newspaper,1},{apples,10},{pears,6},{milk,3}].
Product: [Shop:cost (A) *b | | {A, B} <-Buy]
Summation: Libs:sum ([Shop:cost (A) *b | | {A, B} <-Buy]).
(1) Quick sort: l=[12,6,2,13,2,8,9,10]. Qsort (L).
(2) Pythagoras ternary Group: Libs:pythag (16).
(3) Inflection word: libs:perms ("123").
["123", "132", "213", "231", "312", "321"]
7. Arithmetic expressions
8. Assert:
Max (x, y) when x > Y x;
Max (x, y).
Assert function:
f (x, Y) when is_integer (×), X > Y, y < 6 x;
9. Records: Record
10.case expression:
Filter (P, [p| T])
Case P (H) of
True, [H|filter (P,t}];
False->filter (P,T)
End
Filter (P, []), [].
11.if expression:
12. Built-in function bif
The tuple is converted to a list: Tuple_to_list ({12,cat, "Hello"}).
System times: Time ()
13. Binary data:<<5,10,20>>,<< "Hello" >>
Manipulation: List_to_binary ()
Term_to_binary ()
Binary_to_term ()
Size ()
14. Bit Syntax:<>
File:read_file ("")
15. Dynamic Invocation: Apply (libs, sum, [1,2,3,4]).
16. Module definition:-module (modname).
Introduced:-import (ModName, [FUN/1]). Can not write module name directly reference function name
Export:-export ([NAME1/1, NAME2/2]).
Compilation properties:-compile (Options).
Module version:-VSN (version).
User-defined attribute:-sometag (Value).
Output properties: Attr:module_info ().
Attr:module_info (attributes).
Reference function: Fun mod:remotefunc/arity
Include file:-include (Filename).
-include_lib (Name).
List operator: [1,2,3]++[4,5,6]
[1,2,3]--[2,3]
Binary: k#123
$ syntax: $C represents ASCII
Dictionary: Erase (), put (X, a), get (x), Erase (x)
Short-circuit expression: Epr1 OrElse Epr2. Epr1 Andalse EPR2.
Iii. Erlang Syntax: compiling and running
--------------------------------------
1. Exit: Halt (). Causes the database to recover Q (). Safe exit, equivalent to Init:stop ().
2. Get the Load Path: Code:get_path ().
Get home directory: Init:get_argument (Home).
3. External operation: d:/erl>erl.exe-noshell-s Hello start-s init stop
4. Assistance: Help ().
Erlang Syntax: concurrency (Process similar to people: communication through messages, or broadcast; no shared memory, so no lock required; one dies, the link process is notified)
--------------------------------------
1. Create a process: Pid = spawn (fun)
Spawn (Mod, FuncName, Args).
2. Send message: pid! Message
Mass message: pid1! pid2! pid3...! pidn! Message
Receiving message: Receive ... end.
For example: Pid = Spawn (fun area_server0:loop/0).
Pid! {Rectangle, 6, 10}.
3. Self-id:self ().
Pid! {self (), Message}.
For example: Pid = Spawn (fun area_server1:loop/0).
Area_server1:rpc (Pid, {rectangle, 6, 10}).
4. Set the number of processes: D:/erl>erl +p 500000
Test start time: Process:max (400000).
5. Registration process: Register (Anatom, Pid). Registering process aliases
Unregister (Anatom). Overflow registration process
Whereis (anatom)-Pid | Undefined judge whether to register
Registered (), [Anatom::atom ()] Get all registration process
For example, register clock: Clock:start (Io:format, Fun (), "TICK ~p~n", [Erlang:now ()]).
Stop clock: clock:stop ().
6. Concurrency Error: Link process
v. Erlang syntax: Distributed
---- ----------------------------------
1. Single node test
Start server: Kvs.start ().
Storage: kvs:store ({location, Joe}, " Stockholm ").
kvs:store (weather, raining).
Find: kvs:lookup (weather).
kvs:lookup ({location, Joe}).
2. Two-node test
Start server node:
d:/erl>erl-sname Gandalf
eshell v5.7 (abort with ^g)
( Span class= "__cf_email__" data-cfemail= "187f79767c79747e58627077767f7a71767f74716d" >[email protected] ) 1> Kvs:start ().
true
( [email protected] ) 2>
Caller node:
D:/erl>erl-sname Bilbo
Eshell V5.7 (abort with ^g)
([email protected]) 1> rpc:call ([email protected], KVS, store, [Weather, fine]).
True
([email protected]) 2> rpc:call ([email protected], KVS, lookup, [weather]).
{Ok,fine}
3. Client and server on different machines in the same LAN
4. The client and server are located on different machines on the Internet: to ensure that 4396 port communication is normal, EPMD will use this port
Vi. Erlang Syntax: file
--------------------------------------
1. Read the file: File:consult ("Data1.data").
2. Read an entry: {OK, S} = File:open ("Data1.data", read). Open it
Io:read (S, '). Read an item
Io:get_line (S, '). Read a row
File:close (S). Shut down
3. Find the code base location: Code:which (file).
D:/erl5.7/lib/kernel-2.13/ebin/file.beam
4. Read binary data:
File:read_file ("Data1.data"). Read all to Memory
{OK, S} = File:open ("Data1.data", [Read,binary,raw]). Open it
File:pread (S, 22, 46). Random Read
5. Finding files: Lib_find:files
6. Write file: {OK, S} = File:open ("Data2.data", write). Open it
Io:format (S, "~s~n", ["Hello readers"]). Write
File:close (S). Shut down
7. Random Write:
{OK, S} = File:open ("Data3.data", [Raw,write,binary]). Open it
File:pwrite (S, ten, << "new" >>). Random Write
8. Directory Operation: File:list_dir ("/"). File list
File:make_dir ("abc"). Create a Directory
File:del_dir ("abc"). Delete Directory
9. File properties: File:read_file_info ("Data1.data").
10. File Operation: file:copy ("Data1,data", "/"). Copy
File:delete ("Data1"). Delete
Vii. Erlang syntax: Sockets
---- ----------------------------------
1.Socket Connection Www:socket:nano_get_url ().
2. Start the server: Server:start_nano_server ().
3. Write client: Client:nano_client_eval ("List_to_tuple ([2+3*4,10+20])").
Active: The non-blocking server must receive messages faster than the client sends, or the server will be flooded with messages because the message buffer is full
Passive: block
Mixed: half-block
Viii. Erlang Syntax: Database
--------------------------------------
1.ETS is memory storage, fast
2.DETS is disk storage and can be backed up
3. CREATE TABLE: Ets:new
Dets:open_file
4. Insert: Insert (table, X)
5. Lookup: Lookup (table, Key)
6. Release: Dets:close (TableID) etd:delete (TableID)
7.Mnesia Database:
CREATE TABLE:-record ...
Select all data: Do (QLC ()) ...
Select some columns:
Select by condition:
Connected queries:
Added data: Mnesia:write ()
Delete data: Mnesia:delete ()
Transaction management: Mnesia:transaction (F)
Cancel transaction: Mnesia:abort ()
Startup Table Viewer: Tv:start ().
Ix. Erlang Syntax: OTP
--------------------------------------
1. Support transactions: Rollback with exception snapping
2. Support Hot Code substitution
3. Error log
4. Alarm Management
5. Application Monitor: Appmon:start ().
Ten, Erlang syntax: jinterface
--------------------------------------
Optnode node, listening port can start multiple service nodes, such as [email protected]
Epmd
Optmbox start a mailbox to send and receive mail by default
Link monitors if remote is off
Erlang Basic Grammar Summary