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

Nathan Fiedler nathanfiedler@REDACTED
Thu Jan 8 06:20:59 CET 2015


The maps module would be the first place to look, but it seems to lack
a find(Pred, Map) function. And it doesn't look like proplists would
be of any advantage, either. Nor does Jakob Sievers stdlib2 have
anything helpful here. The best I can offer is to use [H|_T] =
lists:filter(Pred, maps:to_list(Map)), which is shorter, but no more
efficient than what you have so far.

Hopefully someone more knowledgable can help.

n


On Wed, Jan 7, 2015 at 7:56 PM, Harit Himanshu
<harit.subscriptions@REDACTED> wrote:
> 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
>
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list