%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 第八章练习
%% 计算当前加载的所有模块的 函数个数
funscot() ->
Alm = code:all_loaded(),
Cot = lists:map(fun(M) ->
{MI, _} = M,
Module_info = MI:module_info(),
Exports = filter(Module_info, fun(E) -> {K, _}=E, K==exports end),
if
length(Exports)>0 ->
EE = lists:nth(1, Exports),
{_, EL} = EE,
{MI, length(EL)};
true ->
{}
end
end, Alm),
Cot.
%% 计算导出函数最多的模块
max_module() ->
Cot = funscot(),
get_max3(Cot).
% get_max2(Cot).
% get_max(Cot).
% max 方式1
get_max(L) ->
get_max(L, "", 0).
get_max([H|T], Mn, Max) ->
{N,C } = H,
case C>Max of
true ->
get_max(T, N, C);
false ->
get_max(T, Mn, Max)
end;
get_max([], Mn, Max) ->
{Mn, Max}.
% max 方式2
get_max2(L) ->
C = lists:sort(fun(A, B) ->
[{_, CA}, {_, CB}] = [A, B],
CA > CB
end, L),
lists:nth(1, C).
% max 方式3
get_max3(L) ->
get_max3(L, #{}).
get_max3([H|T], M) ->
{N, C} = H,
case is_map_key(cot, M) of
false ->
get_max3(T, #{cot => C, name => N});
true ->
Cot = maps:get(cot, M),
if
Cot < C ->
get_max3(T, M#{cot := C, name := N});
true ->
get_max3(T, M)
end
end;
get_max3([], M) ->
M.
%%% 最常见的函数名
maxfun() ->
FL = funslist(),
lists:nth(1, FL).
funslist() ->
Alm = code:all_loaded(), %所有加载过的模块列表
% 过滤出exports信息
LL = lists:map(fun(M) ->
{MI, _} = M,
Module_info = MI:module_info(),
ML = lists:filter(fun(E) -> {K, _}=E, K==exports end, Module_info),
{_, L} = lists:nth(1, ML),
L
end, Alm),
FL = lmerge(LL, []), % 合并成一个列表
FCM = stfuns(FL, #{}), % 统计每个函数出现的次数
FCL = maps:to_list(FCM), % 转成list
lists:sort(fun(A, B) -> % 排序
[{_, CA}, {_, CB}] = [A, B],
CA > CB
end, FCL).
% 列表合并 {{A, B}, {C, D}, ...} ---> {A, B, C, D, ...}
lmerge([H|T], L) ->
lmerge(T, lists:merge(H, L));
lmerge([], L) ->
L.
%统计函数个数
stfuns([H|T], M) ->
{F, _} = H,
case is_map_key(F, M) of
true ->
C = maps:get(F, M),
stfuns(T, M#{F := C+1});
false ->
stfuns(T, M#{F => 1})
end;
stfuns([], M) ->
M.
%% 只出现过一次的函数
oncefun() ->
FCL = funslist(),
lists:filter(fun(A)->
{_, C} = A,
C =:= 1
end, FCL).
test8() ->
{max_module(), maxfun(), oncefun()}.