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

ok@REDACTED ok@REDACTED
Fri Jan 9 02:26:58 CET 2015


>
> Of course, having a defined function for this:
>
> -spec maps:find(fun ((B) -> boolean()), map(A, B)) -> {ok, {A, B}} |
> not_found.
>
> Could be useful in the long run.

It could, but it would not help with the original poster's
problem, because he wanted to supply an (A,B) -> boolean()
predicate, not a (B) -> boolean() one.

I wonder if the original poster could somehow keep a list
of all the keys, because
    [dummy || K <- Keys,
              case maps:get(K, Map)
                of V -> case Pred(K, V)
                          of true  -> throw({K,V})
                           ; false -> false
                        end
              end]
would do the job without any unwanted allocation, and the
order of the Keys *might* be controlled in a way that gives
'first' a sensible meaning.  (Of course there's a try/catch
around this as well, which I couldn't be bothered typing.)






More information about the erlang-questions mailing list