Map types could do with an equivalent function to Haskell's insertWith

Recently I found myself missing insertWith from Haskell (or generic version)

I was using a map to store the highest number I had found related to each of an "identifier". When a new number arrived, I wanted to insert it in the map if its identifier wasn't already present or compare it to the existing number and insert the larger of the two. In other words have a function that either inserts a value into a map or inserts the output of a function of the existing value and the new values. In this case that function would be std::cmp::max.

I was using a BTreeMap at the time so implemented this via the entry interface, using and_modilfy & or_insert.

map.entry(key).and_modify(|v0| *v0 = std::cmp::max(*v0, value).or_insert(value)

Example in Rust playground.

For this case it would have been very useful to have an insert_with to call like:

map.insert_with(key, value, std::cmp::max)

more generally the 3rd argument being of type Fn(V, V) -> V where V is the value type.

The would be other ways to do this, especially around what the type of the 3rd argument was.

It would be good if this was something that all map types could do.

I'm interested to hear if there's been discussion on this before, or if not then start one.

I imagine there being some issues around the "with" nomenclature already being taken up, and what the best type for a insert_withstyle function should be.

Are there any active efforts to unify the interfaces of map types behind a common trait?


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.