Skip to content

Instantly share code, notes, and snippets.

@vdorr
Created June 29, 2018 12:53
Show Gist options
  • Save vdorr/66a6bfc82fa1ccf6eb14df82b18fbf41 to your computer and use it in GitHub Desktop.
Save vdorr/66a6bfc82fa1ccf6eb14df82b18fbf41 to your computer and use it in GitHub Desktop.
Church encoding of Maybe type (without algebraic data types and typeclasses) & monadic ops
{-# LANGUAGE RankNTypes #-}
-- |Maybe without algebraic data types and typeclasses, including monadic ops
newtype Maybe' a = Maybe' (forall b. b -> (a -> b) -> b)
just' :: a -> Maybe' a
nothing' :: Maybe' a
fromMaybe' :: a -> Maybe' a -> a
maybe' :: b -> (a -> b) -> Maybe' a -> b
fmap' :: (a -> b) -> Maybe' a -> Maybe' b
join' :: Maybe' (Maybe' a) -> Maybe' a
bind' :: Maybe' a -> (a -> Maybe' b) -> Maybe' b
return' :: a -> Maybe' a
just' a = Maybe' (\_ f -> f a)
nothing' = Maybe' (\b _ -> b)
maybe' v f (Maybe' m) = m v f
fromMaybe' a = maybe' a id
fmap' f = maybe' nothing' (just' . f)
join' = maybe' nothing' id
bind' m f = join' (fmap' f m)
return' = just'
instance Show a => Show (Maybe' a) where
show = maybe' "nothing'" (("just' " ++) . show)
main :: IO ()
main = do
print $ just' 1
print $ (nothing' :: Maybe' ())
print $ fmap' (>2) (just' 1)
print $ join' $ return' $ return' 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment