[Erlang 0043] Erlang Code Snippet

  在使用Erlang开发过程中我们会积累一些常用的util方法,同时会把一些方便编译调试的方法放在Erlang的user_default模块.今天翻阅Evernote发现两段非常实用的代码片段,由于google codesearch服务已经关闭,源头不可追溯,好东西不可独享,和大家分享.
本文会持续更新补充内容.

-module(u).
-compile(nowarn_unused_function).
-compile(export_all).

trace(X) -> spawn(fun() -> io:format("~p~n",[X]) end).
trace(X,Y) -> spawn(fun() -> io:format("~p: ~p~n",[X,Y]) end).
traceBinary(X) -> spawn(fun() -> io:format("~p~n",[b2h(X)]) end).

for(Max, Max, F) -> [F(Max)];
for(I, Max, F) -> [F(I)|for(I+1, Max, F)].


b2h(Bin) -> lists:flatten([io_lib:format("~2.16.0B", [X]) || X <- binary_to_list(Bin)]).
h2b(String) -> << << (erlang:list_to_integer([Char], 16)):4/integer >> || Char <- String >>.
t(String)-> h2b(String).
txt(Bin) -> [X || <<X>> <= Bin,X > 32, X < 127, X =/= 45].
b2s(Bin) -> b2s1(binary_to_list(Bin),[]).
b2s1([],Str) -> lists:reverse(Str);
b2s1([H|T],Str) ->
case H > 32 andalso H < 127 andalso H =/= 45 of
true -> b2s1(T,[H|Str]);
false -> b2s1(T,[46,46|Str])
end.

pmap(F, L,Parent) -> [receive {Pid, Res} -> Res end || Pid <- [spawn(fun() -> Parent ! {self(), F(X)} end) || X <- L]].

timer(Time,Fun) -> spawn(fun() -> receive after Time -> ?MODULE:Fun() end end).


signSubtract(A,B) ->
case A<0 of
true -> (erlang:abs(A)-erlang:abs(B))*-1;
false -> (erlang:abs(A)-erlang:abs(B))
end.

signSubtract1(A,B) ->
case A<0 of
true -> (erlang:abs(A)-B)*-1;
_ -> (erlang:abs(A)-B)
end.

%% u:floor(-4.7).
%% Output: -5
floor(X) when X < 0 ->
T = trunc(X),
case (X - T) =:= 0 of
true -> T;
false -> T - 1
end;
floor(X) -> trunc(X).

%%添加协议头
addLen(Bin) ->
Len=erlang:size(Bin)+2,
<<Len:16,Bin/binary>>.

user_default

  [Erlang 0027] Using Record in Erlang Shell 一文中我们已经提到过user_default的用法,不过上次只是小试牛刀用来加载record的定义而已,看看下面的方法;注意这些方法可以直接在Erlang Shell中使用的哦

     Erlang doc link : http://www.erlang.org/documentation/doc-5.4.12/lib/stdlib-1.13.11/doc/html/shell.html

If a command (local function call) is not recognized by the shell, an attempt is first made to find the function in the module user_default, where customized local commands can be placed. If found, then the function is evaluated. Otherwise, an attempt is made to evaluate the function in the module shell_default. The module user_default must be explicitly loaded.

There is some support for reading and printing records in the shell. During compilation record expressions are translated to tuple expressions. In runtime it is not known whether a tuple actually represents a record. Nor are the record definitions used by compiler available at runtime. So in order to read the record syntax and print tuples as records when possible, record definitions have to be maintained by the shell itself. The shell commands for reading, defining, forgetting, listing, and printing records are described below. Note that each job has its own set of record definitions. To facilitate matters record definitions in the modules shell_default and user_default (if loaded) are read each time a new job is started.

-module(user_default).
-compile(export_all).

z(File) ->
Out=compile:file(["./src/", atom_to_list(File),".erl"],
[{outdir,"./ebin/"}, {i,"./src/"},report,debug_info ]),
lm(),
Out.

x(File) ->
Out=compile:file(["./test/", atom_to_list(File),".erl"],
[ {outdir,"./ebin/"}, {i,"./src/"},report,debug_info ]),
lm(),
Out.

s(App) ->
application:start(App).

r(App) ->
application:stop(App),
% os:cmd("ebin ./src/*.erl -I ./include/ +debug_info"),
make:all(),
make:all([load]),
lm(),
application:start(App).

zz(File) ->
?MODULE:z(File),
File:start().

xx(File) ->
?MODULE:x(File),
File:start().

rbb() ->
rb:start([{max,20}]).

rbb(Num) -> rb:start([{max,Num}]).

rbl() -> rb:list().

rbs(Num) ->
rb:show(Num).

test() ->
reloader:reload_modules(reloader:all_changed()).

ll() ->
make:all(),
lm().
lm() -> [c:l(M) || M <- mm()].
mm() -> modified_modules().
modified_modules() ->
[M || {M,_} <- code:all_loaded(), module_modified(M) == true].
module_modified(Module) ->
case code:is_loaded(Module) of
{file,preloaded} ->
false;
{file,Path} ->
CompileOpts = proplists:get_value(compile,Module:module_info()),
CompileTime = proplists:get_value (time,CompileOpts),
Src = proplists:get_value (source,CompileOpts),
module_modified (Path,CompileTime,Src);
_ -> false
end.

module_modified(Path,PrevCompileTime,PrevSrc) ->
case find_module_file(Path) of
false -> false;
ModPath -> case beam_lib:chunks(ModPath, ["CInf"]) of
{ok, {_, [{_, CB}]}} ->
CompileOpts = binary_to_term(CB),
CompileTime = proplists:get_value(time,CompileOpts),
Src = proplists:get_value(source,CompileOpts),
not (CompileTime == PrevCompileTime) and (Src == PrevSrc);
_ -> false
end
end.

find_module_file(Path) ->
case file:read_file_info(Path) of
{ok,_} -> Path;
_ -> % maybe path was changed
case code:where_is_file(filename:basename(Path)) of
non_existing -> false;
NewPath -> NewPath
end
end.
 
 是不是省了好多麻烦?打开Shell试一下吧
 
 晚安!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值