Skip to main content
1 of 2
Kevin Meredith
  • 3.2k
  • 28
  • 51

Implementing Traversable for Coproduct

Given the following from fp-course:

class Functor f where
  (<$>) ::
    (a -> b)
    -> f a
    -> f b

class Functor f => Applicative f where
  pure ::
    a -> f a
  (<*>) ::
    f (a -> b)
    -> f a
    -> f b

class Functor t => Traversable t where
  traverse ::
    Applicative f =>
    (a -> f b)
    -> t a
    -> f (t b)

data Coproduct f g a =
  InL (f a)
  | InR (g a)

Is there a cleaner or more succinct way to implement the following?

instance (Traversable f, Traversable g) =>
  Traversable (Coproduct f g) where
  traverse ::
    Applicative h =>
    (a -> h b)
    -> Coproduct f g a
    -> h (Coproduct f g b)
  traverse f (InL fa) = InL <$> traverse f fa
  traverse f (InR ga) = InR <$> traverse f ga  
Kevin Meredith
  • 3.2k
  • 28
  • 51