Programming Erlang读书笔记5: Advanced SP
所有的BIFs都属于erlang module,如erlang:tuple_to_list()、erlang:time(),但是大部分BIFs都auto-imported了,所以可以直接调用tuple_to_list()、time()erlang module的所有BIFs列表见:http://www.erlang.org/doc/man/erlang.html
Binary是用来存储大量raw data的数据结构
1> <<5, 10, 20>>.<<5,10,20>>
操作Binary的BIFs:
@spec list_to_binary(loList) -> binary()@spec split_binary(Bin, Pos) -> {Bin1, Bin2}@spec term_to_binary(Term) -> Bin@spec binary_to_term(Bin) -> Term@spec size(Bin) -> Int
Bit Syntax:
1> Red = 2.22> Green = 61.613> Blue = 20.204> Mem = <<Red:5, Green:6, Blue:5>>.<<23,180>>5> <<R1:5, G1:6, B1:5>> = Mem.<<23,180>>6> R1.27> G1.618> B1.20
预定义Module属性
-module(modname).-import(Mod, ).-export().-compile(Options).-vsn(Version).
用户自定义Module属性
-SomeTag(Value).
SomeTag必须为一个atom,Value必须为literal term
%% attrs.erl-module(attrs).-vsn(1234).-author({joe,armstrong}).-purpose("example of attributes").-export().fac(1) -> 1;fac(N) -> N * fac(N-1).1> attrs:module_info(attributes).[{vsn,},{author,[{joe,armstrong}]},{purpose,"example of attributes"}]
Boolean Expressions
1> not true.false.2> true and flase.false.3> true or false.true4> true xor false.true
字符集
Erlang源代码按ISO-8859-1(Latin-1)编码处理
Erlang内部没有字符数据类型,字符串事实上并不存在而是由整数列表来表示
Erlang对Unicode解析有限,因为整数列表有限
注释
Erlang里的代码注释以%开始,为单行注释
epp
在Erlang模块编译之前,Erlang的预处理器epp先处理它
epp会扩展源代码里的macros并插入必要的头文件
可以使用命令cmopile:file(M, ['P'])来编译M.erl并将结果输出到M.P文件里
Escape Sequence
\b Backspace 8\d Delete 127\e Escape 27\f Form feed 12\n New line 10\r Carriage return 13\s Space 32\t Tab 9\v Vertical tab 11\NNN \NN \N Octal characters(N is 0..7)\^a..\^z or \^A..\^Z Ctrl+A to Ctrl+Z 1 to 26\' Single quote 39\" Double quote 34\\ Backslash 92\C The ASCII code for C An integer
方法引用
-moduel(x1).-export().square(X) -> X * X.double(L) -> lists:map(fun square/1, L).-module(x2).double(L) -> lists:map(fun x1:square/1, L).
Include Files
Erlang里被引入的文件的扩展名为.hrl
-include(Filename).-include_lib("kernel/include/file.hrl").
List加减
1> ++ .2> -- .
Macros
-define(Constant, Replacement).-define(Func(Var1, Var2, .. , Var), Replacement).
当遇到形如?MacroName的表达式时Macros会被epp扩展:
-define(macro1(X, Y), {a, X, Y}).foo(A) -> ?macro1(A+10, b)
上面的foo(A)会被扩展为:
foo(A) -> {a, A+10, b}
一些预定义的macros提供当前module的信息:
?FILE 当前文件名?MODULE 当前module名?LINE 当前行数
Macros的Control Flow:
-define(Macro).-undef(Macro).-ifdef(Macro).-ifndef(Macro).-else.-endif.
Precess dictionary--Erlang里的HashMap
1> erase().[]2> put(x, 20).undefined3> get(x).204> get().[{x, 20}]5> erase(x).206> get(x).undefined
Short-Circuit Boolean Expression
Expr1 orelse Expr2Expr1 andalso Expr2
Term Comparisons
X > YX < YX =< YX >= YX == YX /= YX =:= YX =/= Y
页:
[1]