Skip to content

Instantly share code, notes, and snippets.

@kputnam
Created April 16, 2016 05:44
Show Gist options
  • Save kputnam/1d1f4ac6be737d26f3aa2a3fe7dce743 to your computer and use it in GitHub Desktop.
Save kputnam/1d1f4ac6be737d26f3aa2a3fe7dce743 to your computer and use it in GitHub Desktop.
Covariant and contravariant functors
-- Covariate functor
class Fun f where
fun :: (a -> b) -> f a -> f b
-- Contravariate functor
class Con f where
con :: (b -> a) -> f a -> f b
-- Function parameterized over input type 'i'
newtype Fin o i = Fin (i -> o)
-- Function parameterized over output type 'o'
newtype Fou i o = Fou (i -> o)
instance Fun (Fou i) where
-- (a -> b) -> Fou i a -> Fou i b
-- (a -> b) -> (i -> a) -> (i -> b)
fun ab (Fou ia) = Fou (\i -> ab (ia i)) -- Fou ib
instance Con (Fin o) where
-- (b -> a) -> Fin o a -> Fin o b
-- (b -> a) -> (a -> o) -> (b -> o)
con ba (Fin ao) = Fin (\b -> ao (ba b))
-- instance Con Ord where
-- -- (b -> a) -> Ord a -> Ord b
-- con ba o = Ord { compare b1 b2 = o.compare (ba b1) (ba b2)
-- , b1 <= b2 = (o.<=) (ba b1) (ba b2)
-- , ...
-- }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment