Skip to content

Instantly share code, notes, and snippets.

@lispyclouds
Last active April 19, 2020 19:33
Show Gist options
  • Save lispyclouds/a6b4a00f6197df22afe4a650030c3fff to your computer and use it in GitHub Desktop.
Save lispyclouds/a6b4a00f6197df22afe4a650030c3fff to your computer and use it in GitHub Desktop.
Monads: Simple made Easy.
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