return 来自 Map 的第一个 {Key, Value} where Predicate 为 true
return first {Key, Value} from Map where Predicate is true
问题更正式的定义是
Write a function map_search_pred(Map, Pred) that returns the first
element {Key,Value} in the map for which Pred(Key, Value) is true.
我的尝试,看起来像
map_search_pred(Map, Pred) ->
M = [{Key, Value} || {Key, Value} <- maps:to_list(Map), Pred(Key, Value) =:= true],
case length(M) of
0 -> {};
_ -> lists:nth(1, M)
end.
当我运行这个时,我得到了正确的答案
1> lib_misc:map_search_pred(#{}, fun(X, Y) -> X =:= Y end).
{}
2> lib_misc:map_search_pred(#{1 => 1, 2 => 2}, fun(X, Y) -> X =:= Y end).
{1,1}
3> lib_misc:map_search_pred(#{1 => 1, 2 => 3}, fun(X, Y) -> X =:= Y end).
{1,1}
4> lib_misc:map_search_pred(#{1 => 2, 2 => 2}, fun(X, Y) -> X =:= Y end).
{2,2}
5>
有问题吗?
问题是效率。
它使用列表理解并运行列表中的所有元素。更好的解决方案是在第一场比赛后 return 。
作为语言的初学者,我不知道有更好的惯用方法来解决这个问题,所以寻找更好的想法和建议
您可以自己遍历列表,并且 return 一旦找到 Pred(Key, Value)
为真的元素:
map_search_pred(Map, Pred) when is_map(Map) ->
map_search_pred(maps:to_list(Map), Pred);
map_search_pred([], _) ->
error;
map_search_pred([{Key,Value}=H|T], Pred) ->
case Pred(Key, Value) of
true ->
{ok, H};
false ->
map_search_pred(T, Pred)
end.
问题更正式的定义是
Write a function map_search_pred(Map, Pred) that returns the first element {Key,Value} in the map for which Pred(Key, Value) is true.
我的尝试,看起来像
map_search_pred(Map, Pred) ->
M = [{Key, Value} || {Key, Value} <- maps:to_list(Map), Pred(Key, Value) =:= true],
case length(M) of
0 -> {};
_ -> lists:nth(1, M)
end.
当我运行这个时,我得到了正确的答案
1> lib_misc:map_search_pred(#{}, fun(X, Y) -> X =:= Y end).
{}
2> lib_misc:map_search_pred(#{1 => 1, 2 => 2}, fun(X, Y) -> X =:= Y end).
{1,1}
3> lib_misc:map_search_pred(#{1 => 1, 2 => 3}, fun(X, Y) -> X =:= Y end).
{1,1}
4> lib_misc:map_search_pred(#{1 => 2, 2 => 2}, fun(X, Y) -> X =:= Y end).
{2,2}
5>
有问题吗?
问题是效率。
它使用列表理解并运行列表中的所有元素。更好的解决方案是在第一场比赛后 return 。
作为语言的初学者,我不知道有更好的惯用方法来解决这个问题,所以寻找更好的想法和建议
您可以自己遍历列表,并且 return 一旦找到 Pred(Key, Value)
为真的元素:
map_search_pred(Map, Pred) when is_map(Map) ->
map_search_pred(maps:to_list(Map), Pred);
map_search_pred([], _) ->
error;
map_search_pred([{Key,Value}=H|T], Pred) ->
case Pred(Key, Value) of
true ->
{ok, H};
false ->
map_search_pred(T, Pred)
end.