题目不写了,能搜到说明缘分。
环境Eshell V9.2
-module(module_statistics).
-export([done/0]).
%% 当前函数不考虑效率,将三个问题分开解答
done() ->
L = [{L1,L2}||{L1,L2} <- code:all_loaded() , filelib:is_file(L2) , is_atom(L1) ],
most_export(L),
%% 合并所有的函数,并转化正list遍历判断
List = lists:merge([ Mod:module_info(exports)|| { Mod, _FILE } <- L]),
Map = list2map(List,maps:new()),
List2 = maps:to_list(Map),
most_popullar(List2,[{void,0}]),
one_function(List2,[]),
done.
%% 模块导出函数最多
most_export(L) ->
% length(Mod:module_info(exports)
% compare length,get the longest one.
List = [ { length(Mod:module_info(exports)) , Mod } || { Mod, _FILE } <- L],
most_export(List,{0,void}).
most_export([],{_Max, Mod}) ->
io:fwrite("most_export_module:~w with ~w exports.~n", [ Mod, _Max]);
most_export([{Max2, _Mod2}=Y|T],{Max, _Mod}=Z) ->
if
Max >= Max2 ->
most_export(T,Z);
Max < Max2 ->
most_export(T,Y)
end.
%% 返回函数名和出现次数映射
list2map([], Map) ->
Map;
list2map([{Fun,_artiy}|T], Map) ->
case maps:is_key(Fun,Map) of
true ->
Num= maps:get(Fun,Map),
Map2 = maps:put(Fun, Num+1, Map),
list2map(T,Map2);
false ->
Map2 = maps:put(Fun, 1, Map),
list2map(T,Map2)
end.
%% 最常见的函数名
most_popullar([],L) ->
io:fwrite("most_func:~p~n", [L]);
most_popullar([{Fun,Num}|T],[{_Fun_max,Num_max}|_T_max]=Z) ->
if
Num > Num_max ->
most_popullar(T,[{Fun,Num}]);
Num =:= Num_max ->
most_popullar(T,[{Fun,Num}|Z]);
Num < Num_max ->
most_popullar(T,Z)
end.
%% 只在一个模块出现过的函数名
one_function([],List) ->
FunList = [ Fun || { Fun,_Num} <- List],
io:fwrite("alone_func_list:~p~n", [FunList]);
one_function([{Fun,Num}|T],List) ->
if
Num =:= 1 ->
one_function(T,[{Fun,Num}|List]);
true ->
one_function(T,List)
end.
执行结果
1> c(module_statistics).
{ok,module_statistics}
2> module_statistics:done().
most_export_module:cerl with 256 exports.
most_func:[{module_info,226}]
alone_func_list:[server_call,to_records,clash,ipv4strict_address,let_body,
is_c_atom,update_c_module,ic,string_table,fun_arity,
add_search,is_c_string,keyreplace,add_socks_methods,nthtail,
update_data_skel,is_c_var,pmap,try_arg,time_difference|...]
done.
第三题的答案太长,就截个局部。
有啥不对的麻烦指点下!