<div dir="ltr">Thanks Nathan</div><div class="gmail_extra"><br><div class="gmail_quote">On Wed, Jan 7, 2015 at 9:20 PM, Nathan Fiedler <span dir="ltr"><<a href="mailto:nathanfiedler@gmail.com" target="_blank">nathanfiedler@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">The maps module would be the first place to look, but it seems to lack<br>
a find(Pred, Map) function. And it doesn't look like proplists would<br>
be of any advantage, either. Nor does Jakob Sievers stdlib2 have<br>
anything helpful here. The best I can offer is to use [H|_T] =<br>
lists:filter(Pred, maps:to_list(Map)), which is shorter, but no more<br>
efficient than what you have so far.<br>
<br>
Hopefully someone more knowledgable can help.<br>
<br>
n<br>
<div><div class="h5"><br>
<br>
On Wed, Jan 7, 2015 at 7:56 PM, Harit Himanshu<br>
<<a href="mailto:harit.subscriptions@gmail.com">harit.subscriptions@gmail.com</a>> wrote:<br>
> The more formal definition of problem is<br>
><br>
> Write a function map_search_pred(Map, Pred) that returns the first element<br>
> {Key,Value} in the map for which Pred(Key, Value) is true.<br>
><br>
> My attempt, looks like<br>
><br>
> map_search_pred(Map, Pred) -><br>
> M = [{Key, Value} || {Key, Value} <- maps:to_list(Map), Pred(Key, Value)<br>
> =:= true],<br>
> case length(M) of<br>
> 0 -> {};<br>
> _ -> lists:nth(1, M)<br>
> end.<br>
><br>
> When I run this, I get correct answer<br>
><br>
> 1> lib_misc:map_search_pred(#{}, fun(X, Y) -> X =:= Y end).<br>
> {}<br>
> 2> lib_misc:map_search_pred(#{1 => 1, 2 => 2}, fun(X, Y) -> X =:= Y end).<br>
> {1,1}<br>
> 3> lib_misc:map_search_pred(#{1 => 1, 2 => 3}, fun(X, Y) -> X =:= Y end).<br>
> {1,1}<br>
> 4> lib_misc:map_search_pred(#{1 => 2, 2 => 2}, fun(X, Y) -> X =:= Y end).<br>
> {2,2}<br>
> 5><br>
><br>
> Problem?<br>
> The problem is efficiency.<br>
> It uses list comprehension and runs for all the elements in the list. The<br>
> better solution would be to return after the first match.<br>
><br>
> As a beginner to language, I do not know a better idiomatic way to solve<br>
> this, so looking for better ideas and suggestions<br>
><br>
> Thank you<br>
><br>
><br>
</div></div>> _______________________________________________<br>
> erlang-questions mailing list<br>
> <a href="mailto:erlang-questions@erlang.org">erlang-questions@erlang.org</a><br>
> <a href="http://erlang.org/mailman/listinfo/erlang-questions" target="_blank">http://erlang.org/mailman/listinfo/erlang-questions</a><br>
><br>
</blockquote></div><br></div>