Created
September 30, 2011 15:23
-
-
Save fumieval/1254089 to your computer and use it in GitHub Desktop.
maybe monad in python
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
""" | |
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