天天看點

Erlang學習筆記大全——我讀阿姆斯特朗的Erlang書

新接觸一門全新的語言,需要系統全面的了解這一預言的所有。于是可以找一本專業的書,我選擇了阿姆斯特朗的Erlang程式設計,通過在讀書過程中記錄關鍵筆記,對于學習新的語言能夠很快的上手。僅供參考。

一、Erlang文法:變量、模式比對

--------------------------------------

1.elr指令:工具欄toolbar:start().

2.%。。。注釋

3.變量首字母大寫,單一指派

4.模式比對

5.原子:hello, 'an atom with'

6.元組tuple:元組嵌套{person,{a,1},{b,2}}

             提取元組字段值Point = {point, 10, 45}  {point, X, Y} = Point

7.清單list:  定義清單ThingsToBuy1 = [{oranges,4}, {newspaper,1}|{ThingsToBuy}]

             提取元素[Buy1|ThingsToBuy2] = ThingsToBuy1.

8.字元串:"hello"

9.q()退出

10.f()釋放變量

二、Erlang文法:函數(面向函數程式設計:函數可以作為參數,也可以作為傳回值,可以使用清單解析、斷言、case/if、二進制、比特位、進制、ASCII碼)

--------------------------------------

1.函數

  編譯:c(geometry)

  運作:geometry:area({rectangle, 10, 5}).

2.匿名函數: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作為函數參數

  映射:lists:map(Double, [1,2,3,4]).

      傳回[2,4,6,8].

  過濾:lists:filter(Even, [1,2,3,4]).

      Even = fun(X) -> (X rem 2) =:= 0 end.

4.傳回fun的函數

  Fruit = [apple,pear,orange].

  MakeTest = fun(L) -> (fun(X) -> lists:member(X,L) end) end.

  IsFruit = MakeTest(Fruit).

  即:IsFruit = fun(X) -> lists:member(X,[apple,pear,orange]) end.

5.循環

  for(Max,Max,F) -> [F(Max)];

  for(I,Max,F)   -> [F(I)|for(I+1,Max,F)]

6.清單解析

  [2*X || X <- L].

  定義:Buy = [{oranges,4},{newspaper,1},{apples,10},{pears,6},{milk,3}].

  乘積:[shop:cost(A)*B || {A,B} <- Buy]

  求和:libs:sum([shop:cost(A)*B || {A,B} <- Buy]).

  (1)快速排序:L=[12,6,2,13,2,8,9,10]. qsort(L).

  (2)畢達哥拉斯三元組:libs:pythag(16).

  (3)變位詞:libs:perms("123").

            ["123","132","213","231","312","321"]

7.算術表達式

8.斷言:

  max(X,Y) when X > Y -> X;

  max(X,Y) -> Y.

  斷言函數:

  f(X,Y) when is_integer(X), X > Y, Y < 6 -> X;

9.記錄:record

10.case表達式:

  filter(P, [P|T]) ->

      case P(H) of

          true -> [H|filter(P,T}];

   false ->filter(P,T)

       end;

  filter(P, []) -> [].

11.if表達式:

12.内建函數BIF

  元組轉換為清單:tuple_to_list({12,cat,"Hello"}).

  系統時間:time()

13.二進制資料:<<5,10,20>>,<<"hello">>

  操縱:list_to_binary()

        term_to_binary()

 binary_to_term()

 size()

14.比特文法:<<X:5, Y:6, Z:5>>

  file:read_file("")

15.動态調用:apply(libs, sum, [1,2,3,4]).

16.子產品定義:-module(modname).

  引入:-import(modname, [fun/1]). 可以不寫子產品名直接引用函數名

  導出:-export([name1/1, name2/2]).

  編譯屬性:-compile(options).

  子產品版本:-vsn(Version).

  使用者定義屬性:-SomeTag(Value).

  輸出屬性:attr:module_info().

            attr:module_info(attributes).

  引用函數:fun Mod:RemoteFunc/Arity

  包含檔案:-include(Filename).

           -include_lib(Name).

  清單操作符:[1,2,3]++[4,5,6]

              [1,2,3]--[2,3]

  進制:K#123

  $文法:$C 表示ASCII

  字典:erase(), put(x, 20),get(x), erase(x)

  短路表達式:Epr1 orelse Epr2.  Epr1 andalse Epr2.

三、Erlang文法:編譯運作

--------------------------------------

1.退出:halt().導緻資料庫要恢複  q().安全退出,等價于init:stop().

2.取得加載路徑:code:get_path().

  取得主目錄:init:get_argument(home).

3.外部運作:D:/erl>erl.exe -noshell -s hello start -s init stop

4.幫助:help().

四、Erlang文法:并發(程序類似于人:通過消息進行溝通,也可以廣播;沒有共享記憶體,是以不需要鎖;某一個死掉,會通知連結程序)

--------------------------------------

1.建立程序:Pid = spawn(Fun)

  spawn(Mod, FuncName, Args).

2.發送消息:Pid!Message

  群發消息:Pid1!Pid2!Pid3...!Pidn!Message

  接收消息:receive ... end.

  例如:Pid = spawn(fun area_server0:loop/0).

        Pid!{rectangle, 6, 10}.

3.自身ID:self().

  Pid!{self(), Message}.

  例如:Pid = spawn(fun area_server1:loop/0).

       area_server1:rpc(Pid, {rectangle, 6, 10}).

4.設定程序數:D:/erl>erl +P 500000

  測試啟動時間:process:max(400000).

5.注冊程序:register(AnAtom, Pid).  注冊程序别名

            unregister(AnAtom).   溢出注冊程序

     whereis(AnAtom) -> Pid | undefined 判斷是否注冊

     registered() -> [AnAtom::atom()] 取得所有注冊程序

  例如注冊時鐘:clock:start(5000, fun() -> io:format("TICK ~p~n", [erlang:now()]) end).

      停止時鐘:clock:stop().

6.并發錯誤:連結程序

五、Erlang文法:分布式

--------------------------------------

1.單節點測試

啟動伺服器:kvs.start().

存儲: kvs:store({location, joe}, "Stockholm").

 kvs:store(weather, raining).

查找: kvs:lookup(weather).

 kvs:lookup({location, joe}).

2.雙節點測試

啟動伺服器節點:

 D:/erl>erl -sname gandalf

 Eshell V5.7  (abort with ^G)

 ([email protected])1> kvs:start().

 true

 ([email protected])2>

調用者節點:

 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.客戶機和伺服器位于同一區域網路的不同機器上

4.客戶機和伺服器位于網際網路的不同機器上:確定4396端口通信正常,epmd會使用這個端口

六、Erlang文法:檔案

--------------------------------------

1.讀取檔案:file:consult("data1.data").

2.讀取一項:{ok, S} = file:open("data1.data", read). //打開

    io:read(S, ''). //讀取一項

    io:get_line(S, ''). //讀取一行

    file:close(S). //關閉

3.查找代碼庫位置:code:which(file).

    d:/erl5.7/lib/kernel-2.13/ebin/file.beam

4.讀取二進制資料:

    file:read_file("data1.data"). //全部讀到記憶體

    {ok, S} = file:open("data1.data", [read,binary,raw]). //打開

    file:pread(S, 22, 46). //随機讀取

5.查找檔案:lib_find:files

6.寫入檔案:{ok, S} = file:open("data2.data", write). //打開

    io:format(S, "~s~n", ["Hello readers"]). //寫入

    file:close(S). //關閉

7.随機寫入:

    {ok, S} = file:open("data3.data", [raw,write,binary]). //打開

    file:pwrite(S, 10, <<"new">>). //随機寫入

8.目錄操作:file:list_dir("/"). //檔案清單

     file:make_dir("abc"). //建立目錄

     file:del_dir("abc"). //删除目錄

9.檔案屬性:file:read_file_info("data1.data").

10.檔案操作:file:copy("data1,data", "/"). //拷貝

            file:delete("data1"). //删除

七、Erlang文法:套接字

--------------------------------------

1.Socket連接配接www:socket:nano_get_url().

2.啟動伺服器:server:start_nano_server().

3.編寫用戶端:client:nano_client_eval("list_to_tuple([2+3*4,10+20])").

主動型:非阻塞 伺服器接收消息的速度必須快于用戶端發送的速度,否則伺服器會因為消息緩沖區塞滿被消息淹沒

被動型:阻塞

混合型:半阻塞

八、Erlang文法:資料庫

--------------------------------------

1.ETS是記憶體存儲,速度快

2.DETS是磁盤存儲,可備份

3.建立表:ets:new

 dets:open_file

4.插入:insert(table, X)

5.查找:lookup(table, Key)

6.釋放:dets:close(tableid) etd:delete(tableid)

7.Mnesia資料庫:

  建立表:-record...

  選取所有資料:do(qlc())...

  選取部分列:

  按條件選取:

  關連查詢:

  增加資料:mnesia:write()

  删除資料:mnesia:delete()

  事務管理:mnesia:transaction(F)

  取消事務:mnesia:abort()

  啟動表檢視器:tv:start().

九、Erlang文法:OTP

--------------------------------------

1.支援事務:使用異常捕捉進行復原

2.支援熱代碼替換

3.錯誤日志

4.警報管理

5.應用程式螢幕:appmon:start().

十、Erlang文法:JInterface

--------------------------------------

OptNode 節點,監聽端口 能夠啟動多個服務節點,如[email protected]

Epmd 

OptMbox 預設啟動一個郵箱 收發郵件

Link 監控遠端是否斷掉