Last active
January 14, 2018 11:05
-
-
Save rcalsaverini/647da3656a1b51adb52e9c3e929f3ea6 to your computer and use it in GitHub Desktop.
Boehm-Berarducci encodings.
This file contains 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 #-} | |
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 |
This file contains 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
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