[Haskell-cafe] Textbook example of instance Foldable ((,) a)

Viktor Dukhovni ietf-dane at dukhovni.org
Tue Nov 24 18:49:14 UTC 2020


On Tue, Nov 24, 2020 at 10:20:58AM +0100, Henning Thielemann wrote:

> > Rather than waiting, it is perhaps more pragmatic to go with a custom
> > Prelude, which one can have now, even for versions of GHC/base, that
> > won't have the feature in question:
> 
> I have such a Prelude:
>     https://hackage.haskell.org/package/prelude-compat
> 
> It helps a bit, but does not fully solve the problem.
> 
> If you use Fold.all on a Map and then switch from Map k a to (Map k a, b) 
> you will again not encounter a warning nor a type error.

Yes, for that one might have to be disciplined and use a monomorphised
variant:

    allMapValues :: (a -> Bool) -> Map k a -> Bool
    allMapValues = Data.Foldable.all

although the risk is only present when (a ~ b), or the predicate is
sufficiently polymorphic (over some superclass of `a` and `b`).

And of course, when refactoring, instead of moving to a 2-tuple, that
brings in possibly unwanted instances, one can instead choose a custom
product type, that does not have a Foldable instance:

    -- coercible to a 2-tuple if/as needed
    newtype T2 a b = T2 { _unT2 :: (a, b) } deriving (Eq, Ord, Show)

to give one's 2-tuples exactly the desired instances and no more.  This
admittedly is not terribly ergonomic.

-- 
    Viktor.


More information about the Haskell-Cafe mailing list