shell 变量 必须 大写 ABC
原子 小写开头加
命令以句点 。 结束
5 div 3 = 1 5 rem 3 = 2 /结果是浮点数
元组 {{,},{,},{{,},{,}}}等等
列表 [{},{},P,N,Person,{{N,Q},{}}]
如果T是列表, [H|T]也是列表。
f() 释放所有绑定过的变量
三章:
total([{Whta,N|T}]) -> shop:cost(Waht) * N +total(T);
total([]) -> 0.
逗号,分割函数调用、数据构造器,模式中的参数
句点.(后跟一个空白符号) shell中分割完整的函数和表达式。
分号; 分割分句
sum(L) ->sum(L,0).
sum([H|T],N) -> sum(T,H+N);
sum([],N) -> N;
sum([H|T]) ->H + sum(T);
sum([]) ->0.
高阶函数。 fun()为匿名函数
lists:map(F,L) fun F应用到列表L 返回新列表
lists:filter(P,L) 满足P(E)为true 的新列表
lists:member(X,L) X是列表L的成员则返回true。
mule =fun(Times) ->( fun(X) -> X*Times end) end.
for 循环:
for(Max,Max,F) -> [F(Max)];
for(I,Max,F) -> [F(I)|for(I+1,Max,F)].
lib-misc:for(1,10,fun(I) -> I end).
lib_misc:for(1,10,fun(I) -> I*I end).
map函数
map(_, []) -> [];
map(F, [H|T]) ->[F(H)|map(F,T)].
total(L) -> sum(map(fun({What,N}) -> shop:cost(What) * N end, L)).
-import(lists, [map/2, sum/1]). 3.6列表解析 程序更简洁
lists:map(fun(X) -> 2*X end, L).
[2*X||X <- L].
total(L) -> lists:sum([shop:cost(A) * B || {A,B} <- L]).
map(F,L) -> [F(X) || X <- L].
[X||Qualifier1,Qualifier2,.....] X:表达式 多个生成器或过滤器
qsort([]) -> [];
qsort([Pivot|T]) ->qsort([X||X <- T,X
=Pivot]).
lists:seq(1,N)
X--Y 列表X中分离出Y
3.7
bnot X, X band Y, X bor Y, X bxor Y, X bsl N, X bsr N, 按位操作。
3.8 断言 程序代码中使用,shell暂不用。
分号;断言集合,任意为true 整个为true
逗号,断言集合,所有为true,整个才为true。
is_constant(X) is_function(X,N)N个参数? is_pid(X) is_port(X) is_reference(X) is_tuple(X),is_record(X,Tag),is_record(X,Tag,N)
abs(X),element(N,X),hd(X),leng(X),node(),node(X),round(X),self(),size(X),trunc(X),tl(X)
四章:
-module(try_test).
-export([generate_exception/1,demo1/0,demo2/0,demo3/0,catcher/1,sqrt/1]).
generate_exception(1) -> a;
generate_exception(2) -> throw(a);
generate_exception(3) -> exit(a);
generate_exception(4) -> {'EXIT',a};
generate_exception(5) -> erlang:error(a).
demo1() -> [catcher(I)|| I <- [1,2,3,4,5]].
catcher(N) ->
try generate_exception(N) of
Val ->{N, normalnnnnnn, Val}
catch
throw:X -> {N, caught, thrown, X};
exit:X -> {N, caught, exited, X};
error:X -> {N, caught, error, X}
end.
demo2() -> [{I,(catch generate_exception(I))} || I <- [1,2,3,4,5]].
sqrt(X) when X < 0 -> {X, (catch erlang:get_stacktrace())};
sqrt(X) -> math:sqrt(X).
demo3() ->
try generate_exception(5)
catch
error:X ->
{X, erlang:get_stacktrace()}
end.
捕获所有异常 要使用
try expr of
Val -> ...
catch
_:_ -> ....
end.
3章的循环 如下两个小程序
for(K,0) ->K;
for(I,N) ->for(I+N,N-1).
(消耗cpu但内存消耗几乎没有)N和内存消耗基本没关系N再大,内存也不会增长。
for2(K,K) ->K;
for2(I,N) ->I + for2(I+1,N).消耗cpu且内存消耗和N成类似正比。
http://yefeng.javaeye.com/blog/268973http://yefeng.javaeye.com/blog/268973
阅读(578) | 评论(0) | 转发(0) |