Created
October 14, 2009 14:31
-
-
Save NicolasT/210117 to your computer and use it in GitHub Desktop.
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
bind = function() # a -> m a | |
return_ = function() # m a -> (f a -> m b) -> m b | |
class Monad(TypeClass): | |
__functions__ = ( | |
bind, | |
return_, | |
) | |
class Maybe(object): pass | |
class _Nothing(Maybe): | |
unapply = lambda _: Nothing | |
Nothing = _Nothing() | |
class Just(Maybe): | |
__init__ = lambda self, value: setattr(self, '_value', value) | |
unapply = lambda self: (Just, self._value) | |
__eq__ = lambda self, other: self._value == other._value | |
instance(Monad, Maybe)( | |
(return_, lambda x: Just(x)), | |
(bind, lambda s, f: match(s)( | |
(Nothing, lambda _: Nothing), | |
((Just, undefined): lambda _, v: f(v)) | |
) | |
) | |
v = bind(Just(1), lambda x: Just(2 * x)) | |
assert v == Just(2) | |
v = bind(Nothing, lambda x: Just(2 * x)) | |
assert v == Nothing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment