[Fwd: updateLookupWithKey confusion]

Jeffrey Yasskin jyasskin at gmail.com
Sat Mar 31 15:22:58 EDT 2007


On 3/31/07, Adrian Hey <ahey at iee.org> wrote:
> Adrian Hey wrote:
> > Hello Folks,
> >
> > Jean-Philippe suggests I put this question to
> > the libraries list. Any thoughts?
>
> Well thinking about this a bit more I propose that both
> updateLookupWithKey and insertLookupWithKey (and possibly
> several other functions) should be deprecated and replaced
> with a more general mechanism that allows users to "roll
> their own" as far as these complex hybrid operations are
> concerned

All of the functions that modify a single value in a single map can be
implemented with
  alterA :: Applicative f => (Maybe v -> f (Maybe v)) -> k -> Map k v
-> f (Map k v)

In particular,

  -- I assume you want the old value out of updateLookup.
  updateLookupWithKey doUpdate key =
    Arrow.first getLast . alterA doChange key
    where
    doChange Nothing = (Last Nothing, Nothing)
    doChange (Just oldValue) = (Last (Just oldValue),
                                doUpdate key oldValue)

and

  insertLookupWithKey combine key value =
    Arrow.first getLast . alterA doChange key
    where
    doChange Nothing = (Last Nothing, Just value)
    doChange (Just oldValue) = (Last (Just oldValue),
                                Just (combine key value oldValue))

I have a start on this at
http://jeffrey.yasskin.info/darcs/hscollection/Data/FiniteMap.hs
(written before I discovered
http://darcs.haskell.org/packages/collections/, so now I'll have to
merge them and send a patch). I haven't implemented alterA on Data.Map
yet; it looks awkward but straightforward.

If you don't intend to modify the map, lookup is probably enough,
although with a slightly more general type for alterA involving "data
Modification v = Delete | LeaveAlone | Replace v", we could subsume
that too...

-- 
Namasté,
Jeffrey Yasskin


More information about the Libraries mailing list