Data.Map, unionWithMaybe

Milan Straka fox at
Mon Jul 29 16:10:47 CEST 2013

Dear Sebastiaan,

> -----Original message-----
> From: Sebastiaan Joosten <sjcjoosten at>
> Sent: 29 Jul 2013, 13:39
> Dear libraries,
> for Data.Map, I needed a "unionWithMaybe" function for my sparse system of linear equations (unionWithMaybe :: Ord k => (a -> a -> Maybe a) -> Map k a -> Map k a -> Map k a). My usage:
> (.+.) = Map.unionWithMaybe (\a b->case a+b of {0->Nothing;s->Just s})
> (I do not think Map.unionWithMaybe can be expressed in terms of other functions without loosing performance, so I recon it would be a nice addition to the library.)
> I built this function myself by modifying the Data.Map implementation, but it would be nice to see it in the official version of Data.Map.
> Here is the file including the modifications I made to it. Feel free to use it, I will agree to whatever license you need to make it public.

The containers version 5.0 (bundled with GHC 7.6) added function
mergeWithKey, which is intended for creating various combining
functions, see

You can define unionWithMaybe as
  unionWithMaybe f m1 m2 = mergeWithKey (const f) id id m1 m2

We are most likely not going to add unionWithMaybe to the API of
containers, because you can define it efficiently using mergeWithKey.

Milan Straka

More information about the Libraries mailing list