Created
November 3, 2020 03:38
-
-
Save baileywickham/325bff9104d5f2ffbf43e4c1fb0fe519 to your computer and use it in GitHub Desktop.
Maybe monad in python
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
from operator import neg | |
class Maybe(object): | |
def __init__(self, v, failed=False): | |
self.v = v | |
self.failed = failed | |
def bind(self, f): | |
if self.failed: | |
return self | |
try: | |
return Maybe(f(self.v)) | |
except: | |
return Maybe(None, True) | |
def __str__(self): | |
return (f'{self.v} {self.failed}') | |
def __le__(self, f): | |
return self.bind(f) | |
def __or__(self, f): | |
return self.bind(f) | |
# Example | |
print(Maybe('123') | int | neg | str) | |
# Note: This doesn't work. It only works for or because the left is evaluated first | |
print(Maybe('123')<=int<=neg<=str) | |
print(Maybe('abc')<=int<=neg<=str) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment