[Haskell-cafe] Custome monoid mappend on HashMap and HashSet values

Simon Marechal simon at banquise.net
Sun May 11 06:45:35 UTC 2014

On 05/11/2014 07:31 AM, John Ky wrote:
> So I went through the whole process of defining newtype, but it was
> quite a long process.  My code below.

I use the lens library, so I don't have to work that hard. I wanted a
Map instance where the <> operation is unionWith (+) :


As you can see, there is a lot less code involved, and I get "for free"
the following equivalents :

M.member k m          -> has (ix k) m
M.lookup k m          -> view (at k) m
M.lookupDefault v k m -> view (at k . non v) m
M.insert k v m        -> (at k ?= v) m
M.delete k m          -> (at k .= Nothing) m
M.map                 -> fmap
M.traverseWithKey     -> itraverse
M.toList              -> itoList

All the union/difference/intersection operations can't be expressed with
lens AFAIK, so if you need them you'll have to rewrite them as you did.

Because of the typeclass approach, the same "lensy" code will work with
any key/value container, so you can refactor without having to touch all
the "M." in your code, and forget whether it is lookupDefault or

More information about the Haskell-Cafe mailing list