[Haskell-cafe] Foldable for (,)

Olaf Klinke olf at aatal-apotheke.de
Wed May 3 21:12:57 UTC 2017

Look at the Stream functor in Data.Stream [1]. Below I will argue by examples that while both Foldable and Traversable instances can be defined, the Foldable instance is less likely to produce terminating functions. 

Streams can be given a Traversable instance easily:

instance Traversable Stream where
  sequenceA (Cons fa fas) = liftA2 Cons fa (sequenceA fas)

For some applicatives this will not terminate. For streams of Maybes, sequenceA will either yield Just an infinite stream or return Nothing. Streams of IO actions also seem fine. 
A possible Foldable instance would suffer the same termination issues due to recursion. But with a monoid, folds over a stream will terminate less often, e.g. 

instance Foldable Stream where
  foldMap f (Cons x xs) = mappend (f x) (foldMap f xs)


  all (xs :: Stream Bool)

will diverge for the constant True stream and terminate for all others. 
-- Olaf

[1] http://hackage.haskell.org/package/Stream-

More information about the Haskell-Cafe mailing list