Created
January 23, 2024 03:14
-
-
Save Mazuh/27f2421c0a8303b1bc9aceef05f7e7f5 to your computer and use it in GitHub Desktop.
Maybe in Python.
This file contains 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
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