[Haskell-cafe] classes for data structures

Denis Bueno dbueno at gmail.com
Wed Feb 6 10:32:14 EST 2008


On Feb 6, 2008 9:40 AM, Henning Thielemann
<lemming at henning-thielemann.de> wrote:
>
>
> On Wed, 6 Feb 2008, Denis Bueno wrote:
>
> > On Feb 6, 2008 9:00 AM, Henning Thielemann
> > <lemming at henning-thielemann.de> wrote:
> > > On Wed, 6 Feb 2008, Matthew Pocock wrote:
> > > > class Buildable b where
> > > >   empty :: b a --makes an empty b with elements of type a
> > > >   insert :: a -> b a -> b a --inserts the new element into the buildable
> > >
> > > How can this interface be used both for lists and maps? [...]
> >
> > One solution is to change the class slightly:
> >
> > class Buildable t x where
> >   empty :: t
> >   insert :: x -> t -> t
> >
> > instance Buildable (Map k a) (k, a) where
> >     empty = Map.empty
> >     insert = uncurry Map.insert
>
> ok, maybe with functional dependency t -> x
>

I'm not sure about that.  It's often convenient to have two instances,
one like the one I gave above, and others involving something that
embeds a key-value pair:

type SomethingWithKV k a = KV {getKV :: (k, a)}
instance Buildable (Map k a) (SomethingWithKV k a) where
  empty = Map.empty
  insert s m = uncurry Map.insert (getKV s) m

I have done this before -- it's very convenient, and I think makes the
code that uses empty and insert more robust, and easier to read.

-- 
                              Denis


More information about the Haskell-Cafe mailing list