Skip to content

Instantly share code, notes, and snippets.

@halcy
Last active February 14, 2022 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halcy/c2df6c4a1d7c80f442ea6ca82f9bc8a2 to your computer and use it in GitHub Desktop.
Save halcy/c2df6c4a1d7c80f442ea6ca82f9bc8a2 to your computer and use it in GitHub Desktop.
# very very simple monad: Maybe
class Maybe:
def __init__(self, value, valid = True):
self.value = value
self.valid = valid
def get_value(self):
return self.value
def has_value(self):
return self.valid
def apply(self, function):
if self.has_value():
try:
return Maybe(function(self.get_value()))
except:
return Maybe(None, False)
else:
return Maybe(None, False)
# A function from int to int that fails
def crashes(x):
return x / 0
# A function from int to int that does not fail
def doesnt_crash(x):
return x + 1
# Lets composit!
a = Maybe(3)
a = a.apply(doesnt_crash)
a = a.apply(doesnt_crash)
a = a.apply(doesnt_crash)
print(a.has_value(), a.get_value())
# Once more with crashing
a = Maybe(3)
a = a.apply(doesnt_crash)
a = a.apply(crashes)
a = a.apply(doesnt_crash)
print(a.has_value(), a.get_value())
# A "Lazy evaluation" monad
class Lazy:
def __init__(self, function, valid = True):
self.function = function
def get_value(self):
return self.function()
def apply(self, function):
def apply_function():
return(function(self.get_value()))
return Lazy(apply_function)
# very useful function to have if you need the number 3
def constant_3():
return 3
# for demonstration purposes
def add_1_and_yell(x):
print("bruh moment")
return x + 1
# time to not perform computation
a = Lazy(constant_3)
a = a.apply(add_1_and_yell)
a = a.apply(add_1_and_yell)
a = a.apply(add_1_and_yell)
a = a.apply(add_1_and_yell)
a = a.apply(add_1_and_yell)
print("Nothing has actually been executed so far")
print(a.get_value())
"""
output:
True 6
False None
Nothing has actually been executed so far
bruh moment
bruh moment
bruh moment
bruh moment
bruh moment
8
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment