Proposal: Add Foldable and Traversable instances for ((,) a)

Yitzchak Gale gale at
Tue Jun 23 08:07:04 EDT 2009

These instances are pretty obvious, and no
more or less trivial than the existing instances
for Prelude types. I have found them to be

> instance Foldable ((,) a) where
>         foldMap f (_, y) = f y
>         foldr f z (_, y) = f y z
>         foldl f z (_, y) = f z y
>         foldr1 _  (_, y) = y
>         foldl1 _  (_, y) = y

> instance Traversable ((,) a) where
>        traverse f (x, y) = (,) x <$> f y

In the spirit of the world's finest legislative bodies,
I am attaching two unrelated amendments to this

One amendment is to add a few additional explicit
method implementations in the Foldable and
Traversable instances for Prelude types.

These might sometimes be slightly more efficient,
and they better match the strictness and style of
the existing explicit method implementations.

For lists:

>         sequence = Control.Monad.sequence

For Maybe:

>         foldMap _ Nothing  = mempty
>         foldMap f (Just x) = f x

>         foldr1 _ Nothing  = error "foldr1 of Nothing"
>         foldr1 _ (Just x) = x

>         foldl1 _ Nothing  = error "foldl1 of Nothing"
>         foldl1 _ (Just x) = x

For arrays:

>         foldl f z = Prelude.foldl f z . elems
>         foldr1 f  = Prelude.foldr1 f  . elems
>         foldl1 f  = Prelude.foldl1 f  . elems

The other amendment is to fix the documentation
for the functions fmapDefault and foldMapDefault
in Data.Traversable. Contrary to what is stated,
these cannot be used as methods in superclasses,
since the superclasses must already exist before
these functions can be defined. Instead, I have
paraphrased what is stated in the documentation
above: that the corresponding superclass methods
should be equivalent to these.

Discussion period: two weeks.

More information about the Libraries mailing list