我需要写一个函数,它会把我最频繁的术语在列表中。例如:
uniq([a, [a,b], [a,b,c]]) -> a
如何使用Erlang递归地完成?
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.
1条答案
按热度按时间mkshixfv1#
不如这样......