Is Biff Either an Applicative?

Viewed 86

The bifunctors library exposes the following data type:

newtype Biff p f g a b = Biff { runBiff :: p (f a) (g b) }

As witnessed in the library, Biff p f g a is a Functor if p is a Bifunctor and g is a Functor.

instance (Bifunctor p, Functor g) => Functor (Biff p f g a) where
  fmap f = Biff . second (fmap f) . runBiff
  {-# INLINE fmap #-}

I suspect (but have not proved) that it is additionally the case that Biff Either f g a is an applicative functor if:

  • f is an Alternative functor
  • g is an Applicative functor

Here is the relevant type tetris:

instance (Alternative f, Applicative g) => Applicative (Biff Either f g a)
  where
  pure a = Biff $ Right $ pure a
  Biff f <*> Biff v = Biff $ go f v
    where
    go (Left  x) (Right _) = Left x
    go (Right _) (Left  x) = Left x
    go (Left  x) (Left  y) = Left $ x <|> y
    go (Right x) (Right y) = Right $ x <*> y

Is this a valid applicative instance?

1 Answers

Said another way, Biff Either f g a is the composition of two applicative functors Either (f a) and g, which is therefore an applicative functor.

Related