Skip to content

Instantly share code, notes, and snippets.

@rcalsaverini
Last active January 14, 2018 11:05
Show Gist options
  • Save rcalsaverini/647da3656a1b51adb52e9c3e929f3ea6 to your computer and use it in GitHub Desktop.
Save rcalsaverini/647da3656a1b51adb52e9c3e929f3ea6 to your computer and use it in GitHub Desktop.
Boehm-Berarducci encodings.
{-# LANGUAGE RankNTypes #-}
import Prelude hiding (Maybe, Just, Nothing, maybe)
data Maybe a = Maybe {maybe :: forall r . r -> (a -> r) -> r}
nothing = Maybe (\nothing' just' -> nothing')
just x = Maybe (\nothing' just' -> just' x)
instance (Show a) => (Show (Maybe a)) where
show xs = maybe xs "Nothing" (\x -> "Just " ++ show x)
instance Functor Maybe where
fmap f xs = maybe xs nothing (\us -> just $ f us)
instance Applicative Maybe where
pure = just
fs <*> xs = maybe fs nothing (\f -> fmap f xs)
instance Monad Maybe where
xs >>= f = maybe xs nothing f
safeHead [] = nothing
safeHead (x:xs) = just x
main = print $ just "omobó" >>= safeHead
class Maybe(object):
def __init__(self, maybe):
self.maybe = maybe
def __call__(self, n, j):
return self.maybe(n, j)
def __repr__(self):
return self("Nothing", lambda x: "Just {}".format(x))
def __rshift__(self, function):
return self(nothing, lambda x: function(x))
def map(self, function):
return self >> (lambda x: just(function(x)))
nothing = Maybe(lambda n, j: n)
just = lambda x: Maybe(lambda n, j: j(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment