Erlang代码片段

来源:百度文库 编辑:神马文学网 时间:2024/05/24 06:31:08
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).

 <> 意思就是取两个单位,每单位8bits。


 unit的默认值取决于type,如果type是integer或者float,则为1,binary为8。

 <> 意思就是取4个单位,每单位8比特,总共4*8比特

1>A = <<1:32/little,1:8/little>>.   %低位在前
<<1,0,0,0,1>>
2> B = <<1:32/big,1:8/big>>.        %高位在前
<<0,0,0,1,1>>

.位操作

    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.

file:write_file("test.txt", "12 13 14 15 16 17 18").

{ok, Bin } = file:read_file (File ),

Rules = string:tokens (erlang:binary_to_list (Bin), "\n").

 case file:open(File, [write]) of
        {ok, FD} ->
            %io:put_chars(FD, Text), <-- ERROR
            ok = file:close(FD),

            file:write_file(File, unicode:characters_to_binary(Text));   <-- HACK

        {error, R} ->
            R1 = file:format_error(R),
            report("could not write file '~s': ~s.", [File, R1]),
            exit(error)

 end.

 或

 file:open(File, [write, {encoding, utf8}])

.日期,时间操作

 {{Y,M,D},{H,M,S}} = calendar:local_time ().

 calendar:day_of_the_week (2009,2,24).

next_day({Y, M, D}) ->
    Day1 = calendar:date_to_gregorian_days (Y, M, D),
    calendar:gregorian_days_to_date (Day1 + 1).

.字符串操作

count_chars(String, Char) ->
    length ([X || X <- String, X == Char]).

 格式化字符串, 像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,"")+3),
        Descr = string:sub_string(T2,1,string:str(T2,"
")-1),
        packages_from_html(T2,[{PName,Descr}|Packages])
    end.

当使用Erlang程序与其它语言程序通讯时,可能需要把一个字符串转换成为Erlang的Term,可以这样实现
{ok, Tokens, _} = erl_scan:string(String),
{ok, Term} = erl_parse:parse_term(Tokens).
注意这里的String需要以句号结尾。

例如在erlang shell下:
> {ok, Tokens, _} = erl_scan:string("{1, {2}, [3]}.").
> {ok, {X, Y, Z}} = erl_parse:parse_term(Tokens).

.ETS/DETS操作

    E = ets:new (my_code, [public, set]),
    ets:match_delete (E,'_'),

    ets:insert (E, {num_files, 0}),
    ets:insert(E, {num_bytes, 0}).

    %% T = ets:new(?MODULE, [{write_concurrency, true}]).

    {ok,?MODULE}=dets:open_file (?MODULE,[{type,set},{file,"fcnum.dets"}]),
    dets:insert(?MODULE, {1, [1,2,3,4,5,6,7]}),

    dets:insert(?MODULE, {1, [7,6,5,4,3,2,1]}),
    dets:close (?MODULE).

>Table = ets:new(foobar, [set, public]).
>ets:tab2list (Table).
[]
> ets:insert(Table, {1}).
true
> ets:insert(Table, {2}).
true
> ets:tab2list(Table).
[{1},{2}]

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

动态改变Mnesia 表结构:

-record (old, {key, val}).
-record (new, {key, val, extra}).
Transformer =
            fun (X) ->
                      #new{key = X#old.key, val = X#old.val, extra = 42}
            end ,
{atomic, ok} = mnesia :transform_table (foo, Transformer, record_info (fields, new)).
例外处理 try
catch _:_ -> ignore end .

嵌套记录 -record(name, {first = "Robert", last = "Ericsson"}). 
-record(person, {name = #name{}, phone}). 
demo() -> 
   P = #person{name= #name{first="Robert",last="Virding"}, phone=123}, 
   First = (P#person.name)#name.first.


发表于: 2009-10-20 ,修改于: 2010-01-01 10:27,已浏览201次,有评论0条 推荐 投诉