Skip to content

Derive instances (Applicative, Monad, ...) for structures lifted over functors

I'll start small: Given that we know how to define various instances for Product GHC could do it automatically.

data P f g a = f a ::: g a deriving (Functor, Applicative, Alternative)

{-
instance (Applicative f, Applicative g) => Applicative (P f g) where
  pure x = pure x ::: pure x
  (f:::g) <*> (x:::y) = (f <*> x) ::: (g <*> y)
-}

And for specific constructors as well

data Q a = [a] :*: Maybe a deriving (Functor, Applicative, Alternative)

{-
instance Applicative Q where
  pure x = [x] :*: Just x
  (f:*:g) <*> (x:*:y) = (f <*> x) :*: (g <*> y)
-}

Alternative

Use GeneralizedNewtypeDeriving

newtype Q a = Q (Product [] Maybe a)
  deriving (Functor, Applicative, Alternative)

pattern (:*:) :: [a] -> Maybe a -> Q a
pattern a :*: b = Q (Pair a b)

Future Work

This should work for a combination of various things, using Const _ deprives us of Alternative

newtype U e a = U (([] `Product` Maybe `Product` Const e) a)
  deriving (Functor, Applicative)

using sums where one summand is identity gives us Applicative / Alternative

-- data Lift f a = Pure a | Other (f a)
import Control.Applicative.Lift

data V a = V ((Lift [] `Product` Maybe) a) 
  deriving (Functor, Applicative, Alternative)

I want to be able to write this directly

data U e a = U [a] (Maybe a) (Const e a)
  deriving (Functor, Applicative)

data V a
  = VL a   (Maybe a)
  | VR [a] (Maybe a)
  deriving (Functor, Applicative, Alternative)

Future, Future Work ==

left-Kan extension

data Lan g h a where
  Lan :: (g b -> a) -> h b -> Lan g h a
  deriving (Functor, Applicative)

codensity

data Endo a = Endo (a -> a)

newtype CodEndo a = CE (forall xx. (a -> Endo xx) -> Endo xx)
  deriving (Functor, Applicative, Monad)

and comonad

data Rose a = a :< [Rose a]
  deriving (Functor, Applicative, Monad, Comonad, ...)
Trac metadata
Trac field Value
Version 8.0.1
Type Bug
TypeOfFailure OtherFailure
Priority normal
Resolution Unresolved
Component Compiler
Test case
Differential revisions
BlockedBy
Related
Blocking
CC
Operating system
Architecture
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information