如何获取Erlang中最常用的元素?

8ehkhllq  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(133)

我需要写一个函数,它会把我最频繁的术语在列表中。例如:

uniq([a, [a,b], [a,b,c]]) -> a

如何使用Erlang递归地完成?

mkshixfv

mkshixfv1#

不如这样......

-module(frequency).

-export([max_frequency/1]).

max_frequency(Values) ->
    CounterMap = build_counter_map(#{}, lists:flatten(Values)),
    key_with_max_value(maps:next(maps:iterator(CounterMap)), -1, none).
    
key_with_max_value (none, _, MaxVal) -> MaxVal;
key_with_max_value ({_Key, Value, Iterator}, CurrentMax, MaxVal) when CurrentMax > Value -> 
    key_with_max_value(maps:next(Iterator), CurrentMax, MaxVal);
key_with_max_value ({Key, Value, Iterator}, _CurrentMax, _MaxVal) ->
    key_with_max_value(maps:next(Iterator), Value, Key).

build_counter_map(CounterMap, []) -> CounterMap;
build_counter_map(CounterMap, [Key|RestOfValues]) ->
    Default = a_special_default_value,
    case maps:get(Key, CounterMap, Default) of
       Default ->
           build_counter_map(maps:put(Key, 1, CounterMap), RestOfValues);
       Value ->
           build_counter_map(maps:put(Key, (Value + 1), CounterMap), RestOfValues)
    end.

相关问题