erlang程序设计8.27练习(2)

本文介绍了一个Erlang程序设计的实用案例,通过编写模块来统计所有已加载模块的导出函数数量、找出最常见的函数名及仅在一个模块中出现的函数名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

erlang程序设计第二版学习笔记-码云


题目不写了,能搜到说明缘分。
环境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.

第三题的答案太长,就截个局部。

有啥不对的麻烦指点下!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值