Skip to content

Add mapWithKeyMonotonic : (k -> a -> (k, b)) -> Map k a -> Map k b #1187

@andreasabel

Description

@andreasabel

I have come across situations where I both want to update the key in an order-preserving way and also change the value.
I suggest to add a function mapWithKeyMonotonic : (k -> a -> (k, b)) -> Map k a -> Map k b and respective variants for the other map types (e.g. mapWithKeyMonotonic : (Int -> a -> (Int, b)) -> IntMap a -> IntMap b).
This structure preserving rewrite can be done in a single pass. The current API only offers an implementation in two passes, mapWithKey and mapKeysMonotonic, and only for the cases where the function k -> a -> (k, b) can be split into (k -> k, k -> a -> b).

Bikeshed colorings:

  1. mapWithKeyMonotonic
  2. mapValuesAndKeysMonotonic
  3. mapKeysAndValuesMonotonic
  4. transformMonotonic
  5. bimapMonotonic if we want to follow https://hackage-content.haskell.org/package/dbus-1.4.2/docs/DBus-Internal-Types.html#v:bimap

I guess I prefer 1 since it is a close variant of existing names, but I am open to alternatives.

Example uses: Derivative of polynomial implemented as Map Natural c of IntMap c: derive = Map.mapWithKeyMonotonic (\ d k -> (d-1, d*k)) . Map.delete 0.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions