erlang小技巧
.列表操作
lists:foreach(fun(X) -> io:format("E=~p~n",[X]) end, [1,2,3]).
lists:duplicate(10, 16#f). % [15,15,15,15,15,15,15,15,15,15]
"abc-123" -> "abc"
no_vsn(Name) -> lists:takewhile(fun($-)->false;(_)-> true end,Name).
"abc-123" -> "123"
vsn(Name) ->
case lists:dropwhile(fun($-)->false;(_)->true end,Name) of
[_Sep|Vsn] -> Vsn;
_ -> "0"
end.
取偶数
EvenN = lists:filter(fun (N) -> N rem 2 == 0 end, lists:seq(1,100))
lists:foldl(fun(F, Last) -> F(Last) end, foo(), [fun whee/1, fun bar/1])
将URL中的空格换成+
UW = lists:map(fun($ )->$+;(C)->C end,Words)
判断是否为空格
is_nb_space(X) ->
lists:member(X, [$\s, $\t]).
>Data = [{"apple", "red"}, {"banana", "yellow"}, {"pear", "white"}].
>lists:keymember("pear",1,Data).
true
>lists:keydelete("banana",1,Data).
[{"apple","red"},{"pear","white"}]
>lists:keyreplace("apple",1,Data,{"tomato", "red"}).
[{"tomato","red"},{"banana","yellow"},{"pear","white"}]
> rd(user,{id,name}). %% 用户记录
> lists:keysearch("wang", #user.name, [#user{id=1,name="li"}, #user{id=2,name="wang"}]).
> {value,#user{id = 2,name = "wang"}}
.二进制操作
-define(BYTE, 8/unsigned-big-integer).
<<C:2/unit:?BYTE>> 意思就是取两个单位,每单位8bits。
unit的默认值取决于type,如果type是integer或者float,则为1,binary为8。
<<C:4/binary, _/binary>> 意思就是取4个单位,每单位8比特,总共4*8比特
.位操作
O2 = ((C1 band 16#03) bsl 4) bor (C2 bsr 4).
. 文件操作
Destination = filename:join([code:root_dir(), "include", no_vsn( New_lib )]), file:make_dir(Destination),
lists:foreach( fun(File) ->
FileName = lists:last(string:tokens(File,"/\\")),
file:copy(File, filename:join([Destination,FileName]))
end, filelib:wildcard(filename:join([Source,"*"])) ).
remove(Path, File) ->
Desc = filename:join([Path,File]),
case filelib:is_dir(Desc) of
true ->
case file:list_dir(Desc) of
{ok,Sub} -> lists:foreach(fun(S) -> remove(Desc,S) end,Sub);
{error,Reason} -> io:format("error: ~p~n",[Reason])
end,
file:del_dir(Desc);
false ->
file:delete(Desc)
end.
uncompress(Archive) ->
case file:read_file(Archive) of
{ok,Tgz} ->
Tar = zlib:gunzip(Tgz),
erl_tar:extract({binary,Tar},[{cwd,code:lib_dir()}]);
Error ->
Error
end.
.日期,时间操作
{{Y,M,D},{H,M,S}} = calendar:local_time().
calendar:day_of_the_week(2009,2,24).
.字符串操作
格式化字符串, 像C语言的sscanf()
Cmd = io_lib:format(\"cd ~s/include; rm ~s; ln -s ../lib/~s/include ~s\", [code:root_dir(), no_vsn( New_lib ), New_lib, no_vsn( New_lib )]),
os:cmd(Cmd);
PN = [erlang:list_to_integer(N) || N <- string:tokens( vsn( Package_that_might_be_newer ), "." )],
packages_from_html(Html,Packages) ->
case string:str(Html,"class=\"package\"") of
0 -> Packages;
Start ->
Sub = string:sub_string(Html,Start),
T1 = string:sub_string(Sub,string:chr(Sub,$>)+1),
PName = string:sub_string(T1,1,string:chr(T1,$<)-1),
T2 = string:sub_string(T1,string:str(T1,"<i>")+3),
Descr = string:sub_string(T2,1,string:str(T2,"</i>")-1),
packages_from_html(T2,[{PName,Descr}|Packages])
end.
. mnesia相关操作
$erl -mnesia dir '"/home/sw2wolf/data"' -s mnesia start
-record(hitNum, {
oid,
hitnum
}).
% 在指定节点创建schema用数据表
install( Nodes ) when is_list( Nodes ) ->
mnesia:stop(),
mnesia:delete_schema( Nodes ),
catch ( mnesia:create_schema( Nodes ) ),
mnesia:start(),
case mnesia:create_table ( hitNum, [
{ disc_copies, Nodes },
{ type, set },
{ attributes, record_info( fields, hitNum) }
] ) of
{ atomic, ok } -> ok;
_Any ->
io:format( "create table error!~n")
end,
mnesia:stop(),
ok.
%增加记录
add_hitnum(HitNums) ->
F = fun() ->
lists:foreach( fun mnesia:write/1, HitNums)
end,
mnesia:transaction( F ).
%查寻
qry_hitnum() ->
Q = qlc:q( [X || X <- mnesia:table(hitNum)] ),
F = fun() -> qlc:e( Q ) end,
{ atomic, Val } = mnesia:transaction( F ),
lists:sort(Val).
lists:foreach(fun(X) -> io:format("E=~p~n",[X]) end, [1,2,3]).
lists:duplicate(10, 16#f). % [15,15,15,15,15,15,15,15,15,15]
"abc-123" -> "abc"
no_vsn(Name) -> lists:takewhile(fun($-)->false;(_)-> true end,Name).
"abc-123" -> "123"
vsn(Name) ->
case lists:dropwhile(fun($-)->false;(_)->true end,Name) of
[_Sep|Vsn] -> Vsn;
_ -> "0"
end.
取偶数
EvenN = lists:filter(fun (N) -> N rem 2 == 0 end, lists:seq(1,100))
lists:foldl(fun(F, Last) -> F(Last) end, foo(), [fun whee/1, fun bar/1])
将URL中的空格换成+
UW = lists:map(fun($ )->$+;(C)->C end,Words)
判断是否为空格
is_nb_space(X) ->
lists:member(X, [$\s, $\t]).
>Data = [{"apple", "red"}, {"banana", "yellow"}, {"pear", "white"}].
>lists:keymember("pear",1,Data).
true
>lists:keydelete("banana",1,Data).
[{"apple","red"},{"pear","white"}]
>lists:keyreplace("apple",1,Data,{"tomato", "red"}).
[{"tomato","red"},{"banana","yellow"},{"pear","white"}]
> rd(user,{id,name}). %% 用户记录
> lists:keysearch("wang", #user.name, [#user{id=1,name="li"}, #user{id=2,name="wang"}]).
> {value,#user{id = 2,name = "wang"}}
.二进制操作
-define(BYTE, 8/unsigned-big-integer).
<<C:2/unit:?BYTE>> 意思就是取两个单位,每单位8bits。
unit的默认值取决于type,如果type是integer或者float,则为1,binary为8。
<<C:4/binary, _/binary>> 意思就是取4个单位,每单位8比特,总共4*8比特
.位操作
O2 = ((C1 band 16#03) bsl 4) bor (C2 bsr 4).
. 文件操作
Destination = filename:join([code:root_dir(), "include", no_vsn( New_lib )]), file:make_dir(Destination),
lists:foreach( fun(File) ->
FileName = lists:last(string:tokens(File,"/\\")),
file:copy(File, filename:join([Destination,FileName]))
end, filelib:wildcard(filename:join([Source,"*"])) ).
remove(Path, File) ->
Desc = filename:join([Path,File]),
case filelib:is_dir(Desc) of
true ->
case file:list_dir(Desc) of
{ok,Sub} -> lists:foreach(fun(S) -> remove(Desc,S) end,Sub);
{error,Reason} -> io:format("error: ~p~n",[Reason])
end,
file:del_dir(Desc);
false ->
file:delete(Desc)
end.
uncompress(Archive) ->
case file:read_file(Archive) of
{ok,Tgz} ->
Tar = zlib:gunzip(Tgz),
erl_tar:extract({binary,Tar},[{cwd,code:lib_dir()}]);
Error ->
Error
end.
.日期,时间操作
{{Y,M,D},{H,M,S}} = calendar:local_time().
calendar:day_of_the_week(2009,2,24).
.字符串操作
格式化字符串, 像C语言的sscanf()
Cmd = io_lib:format(\"cd ~s/include; rm ~s; ln -s ../lib/~s/include ~s\", [code:root_dir(), no_vsn( New_lib ), New_lib, no_vsn( New_lib )]),
os:cmd(Cmd);
PN = [erlang:list_to_integer(N) || N <- string:tokens( vsn( Package_that_might_be_newer ), "." )],
packages_from_html(Html,Packages) ->
case string:str(Html,"class=\"package\"") of
0 -> Packages;
Start ->
Sub = string:sub_string(Html,Start),
T1 = string:sub_string(Sub,string:chr(Sub,$>)+1),
PName = string:sub_string(T1,1,string:chr(T1,$<)-1),
T2 = string:sub_string(T1,string:str(T1,"<i>")+3),
Descr = string:sub_string(T2,1,string:str(T2,"</i>")-1),
packages_from_html(T2,[{PName,Descr}|Packages])
end.
. mnesia相关操作
$erl -mnesia dir '"/home/sw2wolf/data"' -s mnesia start
-record(hitNum, {
oid,
hitnum
}).
% 在指定节点创建schema用数据表
install( Nodes ) when is_list( Nodes ) ->
mnesia:stop(),
mnesia:delete_schema( Nodes ),
catch ( mnesia:create_schema( Nodes ) ),
mnesia:start(),
case mnesia:create_table ( hitNum, [
{ disc_copies, Nodes },
{ type, set },
{ attributes, record_info( fields, hitNum) }
] ) of
{ atomic, ok } -> ok;
_Any ->
io:format( "create table error!~n")
end,
mnesia:stop(),
ok.
%增加记录
add_hitnum(HitNums) ->
F = fun() ->
lists:foreach( fun mnesia:write/1, HitNums)
end,
mnesia:transaction( F ).
%查寻
qry_hitnum() ->
Q = qlc:q( [X || X <- mnesia:table(hitNum)] ),
F = fun() -> qlc:e( Q ) end,
{ atomic, Val } = mnesia:transaction( F ),
lists:sort(Val).
莫愁前路无知己,天下无人不识君。