Created
June 29, 2018 12:53
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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