[erlang-questions] How to return first {Key, Value} from Map where Predicate is true

Harit Himanshu harit.subscriptions@REDACTED
Thu Jan 8 04:56:01 CET 2015


The more formal definition of problem is

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.

My attempt, looks like

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.

When I run this, I get correct answer

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>

*Problem?*
The problem is efficiency.
It uses list comprehension and runs for all the elements in the list. The
better solution would be to return after the first match.

As a beginner to language, I do not know a better idiomatic way to solve
this, so looking for better ideas and suggestions

Thank you
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150107/982e66d4/attachment.htm>


More information about the erlang-questions mailing list