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

Robert Wilkinson bob@REDACTED
Thu Jan 8 11:21:07 CET 2015

On Wed, Jan 07, 2015 at 07:56:01PM -0800, Harit Himanshu 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.


> *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

Hello Harit

I have some problem with your intent. A map is not ordered (afaik -
or it will/may be implementation dependent) and so the concept of
*first* is misguided? (it may depend on external factors)

Maybe the function should return when *any* key/value pair 
satisfies the predicate.

Sorry if I am being over pedantic!


More information about the erlang-questions mailing list