Welcome! Please see the About page for a little more info on how this works.

+2 votes
in Collections by
retagged by

Hi!

Does it make sense to define filter-keys/filter-vals functions for map which takes a map and a predicate and returns a map satisfied predicate?

For example, there is an utility lib called medley and it defines such functions for maps as filter-keys, filter-vals and some others.

It seems that there is a reason for not having it in the core lib.
Using core lib i can use select-keys to query a map with a vector of keys and get a map with requested keys if map has it but there is no more advanced query functions for map except powerful reduce-kv which mixes condition + new map building.

Clojure set lib defines a set/select function allowing to apply a predicate over a set and gets a set as a result.

Any ideas why there is no similar functions for maps?

2 Answers

+1 vote
by
selected by
 
Best answer

In general, most map functions in Clojure treat the map as an index, manipulated in ways that leverage and preserve key-based O(~1) access performance, rather than a sequential collection of entries. Providing functions that require a full traversal and modification of the map are a bit at odds with that. I don't recall having considered these functions for inclusion in the past.

by
By "modification of the map" you mean changing the count of map entries, right?
I am trying to align the idea of working with maps as with an index with update-keys/update-vals functions in the clojure.core. These functions transforms keys or vals but does not change the count of map entries (if transform function return unique value for its input).
by
edited by
It's not about the count but about whether you are walking through every kv entry, but `update-keys` and `update-vals` are good similar functions.

`filter-keys/vals` implies a more generic operation that applies a transducer to a k or v. `reduce-kv` and `transduce` both kind of cover this but the former doesn't handle transducers and they don't have k v args; and the latter doesn't handle the "map"-ness. So maybe there is a `transduce-keys` and/or `transduce-vals` variant that would be useful.

https://github.com/cgrand/xforms has a lot of thinking about this already too wrt maps and kv functions. I'm not sure we would end up in exactly the same place as that but seems like an interesting thing to think about.
+2 votes
by
...