Skip to content

Instantly share code, notes, and snippets.

@Mazuh
Created January 23, 2024 03:14
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 Mazuh/27f2421c0a8303b1bc9aceef05f7e7f5 to your computer and use it in GitHub Desktop.
Save Mazuh/27f2421c0a8303b1bc9aceef05f7e7f5 to your computer and use it in GitHub Desktop.
Maybe in Python.
class Maybe:
condition_fn = None
then_fn = None
otherwise_fn = None
def __init__(self, condition_fn):
self.condition_fn = condition_fn
def then(self, then_fn):
self.then_fn = then_fn
return self
def otherwise(self, otherwise_fn):
self.otherwise_fn = otherwise_fn
return self
def do(self):
if self.condition_fn():
return self.then_fn()
if self.otherwise_fn is not None:
return self.otherwise_fn()
return None
def print_even_or_odd(n):
Maybe(lambda: n % 2 == 0) \
.then(lambda: print(f"{n} is even!")) \
.otherwise(lambda: print(f"{n} is odd!")) \
.do()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment