Skip to content

Instantly share code, notes, and snippets.

@fumieval
Created September 30, 2011 15:23
Show Gist options
  • Save fumieval/1254089 to your computer and use it in GitHub Desktop.
Save fumieval/1254089 to your computer and use it in GitHub Desktop.
maybe monad in python
"""
Maybe monad in Python
use `Just(x)` instead of `return x`
"""
class Maybe():
def __and__(self, k): # a >>= b
if self.__class__ == __Nothing:
return Nothing
elif self.__class__ == Just:
return k(self.dim)
def __rshift__(self, k):
return self & (lambda _: k)
class _Maybe__Nothing(Maybe):
def __repr__(self):
return "Nothing"
Nothing = _Maybe__Nothing()
class Just(Maybe):
def __init__(self, x):
self.dim = x
def __repr__(self):
return "Just(%r)" % self.dim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment