The simplest alternative is to use :maps.filter(). It's not as easy to pipe
into, but that's a minor concern for me.

As another alternative, this should be faster and have lower memory
footprint than using Enum, although you'd need to benchmark it as well to
be sure:

map
|> Stream.filter(predicate)
|> Map.new()

Personally, I would love to see an extension for Map.new() that would allow
filtering the first argument in addition to the currently supported
transformation. So instead of the current

Map.new(enumerable, fn thing -> {key, val} end)

we could have

Map.new(enumerable, map: fn thing -> {key, val} end, filter: fn {_key, val}
-> predicate(val) end)

Such an extension is unlikely to be added though because it would be
another way of doing what is already possible with Enum, Stream, and Map.

On Thu, Aug 15, 2019 at 10:29 AM Roman Smirnov <pom...@gmail.com> wrote:

> Since OTP 18 there is a pretty convenient function :maps.filter
> <http://erlang.org/doc/man/maps.html#filter-2>.
>
> I think it would be nice to have Map.filter(map, predicate) in Elixir as
> well instead of doing
>
>
> map|> Enum.filter(predicate)|> Enum.into(%{})
>
>
> or
>
> for {key, value} <- map, some_filter(key, value), into: %{}, do: {key, value}
>
> The first one alternative is slower, b/c of 2-step transformation, and the
> second one consume more memory, could not be piped and has a lack
> of expressiveness (too imperative way to do a simple filtration).
> There were benchmarks and a small discussion in PR:
> https://github.com/elixir-lang/elixir/pull/9292, but the discussion
> should be moved to this mailing list.
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "elixir-lang-core" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to elixir-lang-core+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/elixir-lang-core/5d403c4a-91f8-4c4d-8dc0-297185a2aed8%40googlegroups.com
> <https://groups.google.com/d/msgid/elixir-lang-core/5d403c4a-91f8-4c4d-8dc0-297185a2aed8%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elixir-lang-core+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/CAAPY6eO5aDifRxHxv7QtD4%3Di_bYbUw1sphxMhq4jEjuR9naPSQ%40mail.gmail.com.

Reply via email to