[Proposal] Map.filter_by_key/2, filter_by_value/2, and corresponding reject functions

47 views
Skip to first unread message

Tyler Young

unread,
Nov 7, 2021, 3:19:02 PM11/7/21
to elixir-lang-core

I’m so excited that 1.13 is bringing Map.filter/2 and Map.reject/2. The performance improvements over the alternatives are nice, but I think making the author’s intent more clear is the biggest win.

With that said, I’d love to extend this with corresponding functions for filtering just based on the keys or values of the map. In practice, you're almost always discarding one of the two; you almost never see a map filtering on both the key and value at the same time.

While there's probably no performance benefit to be had, I think the added expressivity is worth it. Consider:

is_odd = fn val -> rem(val, 2) == 1 end
numbers = %{one: 1, two: 2, three: 3, four: 4}

Map.filter(numbers, fn {_key, val} -> is_odd(val) end)
Map.filter_by_value(numbers, &is_odd/1)


Cutting down on the boilerplate of unwrapping the key-value tuple makes this much more readable in my opinion.

If we wanted these, my suggestions would be:
  • Map.filter_by_key/2
  • Map.filter_by_value/2
  • Map.reject_by_key/2
  • Map.reject_by_value/2
  • Keyword versions of all four of the above
I realize this isn't a very "general" sort of library feature, and clearly it doesn't accomplish anything that wasn't possible before, so it might not be the direction the core folks want the language to go. I figured it can't hurt to pitch it, though. ☺️

Zach Daniel

unread,
Nov 7, 2021, 3:21:01 PM11/7/21
to elixir-l...@googlegroups.com
Just want to chime in and say that I somehow missed the addition of `Map.map`, `Map.filter` and `Map.reject` and I am *thrilled* by those additions :D

Sent via Superhuman


I realize this isn't a very "general" sort of library feature, and clearly it doesn't accomplish anything that wasn't possible before, so it might not be the direction the core folks want the language to go. I figured it can't hurt to pitch it, though. ☺

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/9b6acd9c-d1bd-4286-b733-3405e177ecc8n%40googlegroups.com.

Reply all
Reply to author
Forward
0 new messages