RFC: Collection Framework, reprise.

Sebastian Sylvan sebastian.sylvan at gmail.com
Thu Feb 23 12:25:15 EST 2006

Sometimes you want to add an element, or update an existing element if
one exists.

You may, for example, want to store a list of values at each node in a
Map, so if a key doesn't exist you add a singleton list, if the key
does exist you add the new value to the list with that key. The value
type is thus of a *different* type than the values that are inserted.

insertWith' :: (b -> a -> a) -> (b -> a) -> k -> a -> c -> c

Where the second function is used only in the "not existing" case.

So the case described above could be done like so

myInsert = insertWith' (:) (:[])

That is, if the key exists, the value is simply added to the front of
the list, if the key doesn't exist, it's added to an empty list.

This is more general than insertWith, so maybe insertWith could be
defined outside the class using this... insertWith' is probably not
the best name...

Or... you could generalise adjust instead...

adjust :: (Maybe v -> v) -> k -> c -> c

myInsert k v =  adjust f k
   where f Nothing = [v]
            f (Just vs) = v:vs

I think I may like this better... It moves the "insertion type is
different from stored type"-thing outside the type signatures...

Sebastian Sylvan
UIN: 44640862

More information about the Libraries mailing list