Created
November 15, 2022 16:28
-
-
Save rob-smallshire/85e0b67818605935c9f7316a5871a786 to your computer and use it in GitHub Desktop.
A maybe (?Monad)
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
import random | |
class Maybe: | |
def __init__(self, item=None): | |
self._item = item | |
def __iter__(self): | |
if self._item is not None: | |
yield self._item | |
def __len__(self): | |
return int(self._item is not None) | |
def map(self, f): | |
if self._item is not None: | |
return Maybe(f(self._item)) | |
return Maybe() | |
def __repr__(self): | |
if self._item is not None: | |
return repr(self._item) | |
return None | |
def double(x): | |
return 2*x | |
def triple(x): | |
return 3*x | |
def just(item): | |
return Maybe(item) | |
def nothing(): | |
return Maybe() | |
thing = random.choice( | |
[ | |
just(5), | |
nothing(), | |
] | |
) | |
m = thing.map(double).map(triple) | |
for item in m: | |
print(item) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment