Skip to content

Instantly share code, notes, and snippets.

@NicolasT
Created October 14, 2009 14:31
Show Gist options
  • Save NicolasT/210117 to your computer and use it in GitHub Desktop.
Save NicolasT/210117 to your computer and use it in GitHub Desktop.
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