Programming Erlang读书笔记3: Sequential Programming

阅读更多
module是Erlang代码的基本单元,我们写的所有function都存储在module里面,module存储在.erl文件里面
module编译成.beam文件后方可运行

在Erlang_HOME建立一个名为.erlang的文件:
io:format("consulting .erlang in ~p~n", [element(2, file:get_cwd())]).
%% Edit to the directory where you store your code
c:cd("C:/Program Files/erl5.6/work").
io:format("Now in:~p~n", [element(2, file:get_cwd())]).

这样启动Erlang自带的Windows程序时会自动切换到work目录

funs是匿名方法:
1> Z = fun(X) -> 2*X end.
2> TempConvert = fun({c, C}) -> {f, 32 + C*9/5};
                    ({f, F}) -> {c, (F-32)*5/9}
                 end.


返回funs的方法和可以接受funs作为参数的方法被称为higher-order方法
接受funs作为参数的方法:
1> L = [1,2,3,4].
[1,2,3,4]
2> lists:map(Double, L).
[2,4,6,8]
3> lists:filter(Even, L).
[2,4]

返回funs的方法:
1>Fruit = [apple, pear, orange].
[apple, pear, orange]
2> MakeTest = fun(L) -> (fun(X) -> lists:member(X, L) end) end.
#Fun
3> IsFruit = MakeTest(Fruit).
#Fun
4> IsFruit(pear).
true
5> IsFruit(dog).
false
6> lists:fitler(IsFruit, [dog, orange, cat, apple, bear]).
[orange, apple]


Erlang没有for循环,但我们可以自己定义一个:
for(Max, Max, F) -> [F(Max)];
for(I, Max, F) -> [F(I)|for(I+1, Max, F)].

1> lib_misc:for(1,10,fun(I) -> I end).
[1,2,3,4,5,6,7,8,9,10]


module用来声明本module名
export用来导出本module的公开方法
import用来导入其它module的公开方法

使用List Comprehension([F(X) || X <- L])来简化编程和增加可读性:
1> L = [1,2,3,4,5].
[1,2,3,4,5]
2> lists:map(fun(X) -> 2*X end, L).
[2,4,6,8,10]
3>[2*X || X <- L].
[2,4,6,8,10]


用List Comprehension实现Quicksort:
qsort([]) -> [];
qsort([Pivot|T]) ->
    qsort([X || X <- T, X < Pivot]) ++ [Pivot] ++ qsort([X || X <- T, X >= Pivot]).


用List Comprehension实现Pythagorean Triplets:
pythag(N) ->
    [ {A,B,C} ||
        A <- lists:seq(1,N),
        B <- lists:seq(1,N),
        C <- lists:seq(1,N),
        A+B+C =< N,
        A*A+B*B =:= C*C
    ].


算数表达式
Op           Argument Type Priority
+X               Number       1
-X               Number       1
X*Y              Number       2
X/Y              Number       2
bnot X           Integer      2
X div Y          Integer      2
X rem Y          Integer      2
X band Y         Integer      2
X+Y              Number       3
X-Y              Number       3
X bor Y          Integer      3
X bxor Y         Integer      3
X bsl N          Integer      3
X bsr N          Integer      3

优先级为1的先执行,然后是2,and so on
可以用括号改变优先级,括号内的先执行
相同优先级的按从左到右执行

Guard是Erlang里的的一种表达式,关键字为when
max(X, Y) when X > Y -> X;
max(X, Y) -> Y.


Guard Sequence是一个或多个Guard,用“;”隔开
G1;G2;...;Gn中至少有一个Guard为true的话则这个Guard Sequence为true

Guard是一个或多个Guard表达式,用“,”隔开
GuardExpr1,GuardExpr2,...,GuardExprN中所有Guard表达式都为true时为true

合法的Guard表达式:
1,The atom true
2,Other constants(terms and bound variables),all evaluate to false
3,Calls to the guard predicates and to the BIFs
4,Term comparisons
5, Arithmetic expressions
6, Boolean expressions
7, Short-circuit boolean expressions

Guard 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)


Guard true用于在if表达式中catch all:
if
    Guard -> Expressions;
    Guard -> Expressions;
    ...
    true -> Expressions
end


Guard buit-in functions:
abs(X)
element(N, X)
float(X)
hd(X)
length(X)
node()
node(X)
round(X)
self()
size(X)
trunc(X)
tl(X)


Record用来给Tuple的元素起名字:
-record(todo, {status=reminder, who=joe,text}).

Record的filed可以有默认值
Record定义可以在Erlang源代码里或者放在外部.hrl文件里并被Erlang源代码所引入
我们可以在Eshell里使用rr()方法来读取Record定义:
1> rr("records.hrl").
[todo]

创建和修改Record:
2> X=#todo{}.
#todo{status = reminder, who = joe, text = undefined}
3> X1=#todo{status=urgent, text="Fix errata in book"}.
#todo{status = urgent, who = joe, text = "Fix errata in book"}
4> X2=X1#todo{status=done}.
#todo{status = done, who = joe, text = "Fix errata in book"}
5> #todo{who=W, text=Txt} = X2.
#todo{status = done, who = joe, text = "Fix errata in book"}
6> W.
joe
7> Txt.
"Fix errata in book"
8> X2#todo.text.
"Fix errata in book"


Record是Tuple的伪装:
1> X.
#todo{status = done, who = joe, text = "Fix errata in book"}
2> rf(todo).
ok
3> X.
{todo, done, joe, "Fix errata in book"}


case表达式:
case Expression of
    Pattern1 [when Guard1] -> Expr_seq1;
    Pattern2 [when Guard2] -> Expr_seq2;
    ...
end


if表达式:
if
    Guard1 ->
        Expr_seq1;
    Guard2 ->
        Expr_seq2;
    ...
end


将一个整数List按奇偶分成两个List:
odds_and_evens(L) ->
  odds_and_evens(L, [], []).

odds_and_evens([H|T], Odds, Evens) ->
  case (H rem 2) of
    1 -> odds_and_evens(T, [H|Odds], Evens);
    0 -> odds_and_evens(T, Odds, [H|Evens])
  end;
odds_and_evens([], Odds, Evens) ->
  {lists:reverse(Odds), lists:reverse(Evens)}.

你可能感兴趣的:(Erlang,读书,Apple,C,C++)