-
-
Save TimoKramer/cc988bdf4906d3f95a4c7a30fd42f078 to your computer and use it in GitHub Desktop.
Monads: Simple made Easy.
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 functools import reduce | |
| class Maybe(object): | |
| def __str__(self): | |
| return "Maybe" | |
| class Something(Maybe): | |
| def __init__(self, value): | |
| self.value = value | |
| def __str__(self): | |
| return f"Something {self.value}" | |
| class Nothing(Maybe): | |
| def __str__(self): | |
| return "Nothing" | |
| def read_and_add(prev): | |
| try: | |
| n = int(input("Enter a number: ")) | |
| return Something(prev + n) | |
| except Exception: | |
| return Nothing() | |
| def bind(m, f): | |
| if isinstance(m, Something): | |
| return f(m.value) | |
| else: | |
| return Nothing() | |
| def unit(value): | |
| return Something(value) | |
| def chain(value, *functions): | |
| return reduce(bind, functions, value) | |
| def sum_of_3_nums(): | |
| return chain( | |
| unit(0), | |
| read_and_add, | |
| read_and_add, | |
| read_and_add | |
| ) | |
| if __name__ == '__main__': | |
| r = sum_of_3_nums() | |
| print(r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment