Skip to content

Instantly share code, notes, and snippets.

@mneumann
Created July 26, 2023 17:25
Show Gist options
  • Save mneumann/3a4578032f4ee52d511e21c468f9fded to your computer and use it in GitHub Desktop.
Save mneumann/3a4578032f4ee52d511e21c468f9fded to your computer and use it in GitHub Desktop.
10-minute option.py hack
class Option:
def __init__(self, *args):
if len(args) == 0:
self._tag = "None"
self._value = None
elif len(args) == 1:
self._tag = "Some"
self._value = args[0]
else:
raise RuntimeError("Invalid arity")
@staticmethod
def some(value):
return Option(value)
@staticmethod
def none():
return Option()
def is_some(self) -> bool:
return self._tag == "Some"
def is_none(self) -> bool:
return self._tag == "None"
def map(self, f):
if self._tag == "Some":
return Option(f(self._value))
else:
return self
def unwrap(self):
if self._tag == "Some":
return self._value
else:
raise RuntimeError("unwrap")
def unwrap_or(self, default_value):
if self._tag == "Some":
return self._value
else:
return default_value
def unwrap_or_else(self, f):
if self._tag == "Some":
return self._value
else:
return f()
def or_(self, optb):
if self.is_some():
return self
else:
return optb
def or_else(self, f):
if self.is_some():
return self
else:
return f()
def and_(self, optb):
if self.is_none():
return self
else:
return optb
def and_then(self, f):
if self.is_none():
return self
else:
return f(self.unwrap())
opt = Option(1).map(lambda x: x + 1).and_then(lambda x: Option.none()).or_(Option(4))
print(opt.unwrap_or_else(lambda: 4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment