Skip to content

Instantly share code, notes, and snippets.

@cafuneandchill
Last active August 4, 2022 02:34
Show Gist options
  • Save cafuneandchill/98346a64f1157aaf8eb82b9b3fd384b4 to your computer and use it in GitHub Desktop.
Save cafuneandchill/98346a64f1157aaf8eb82b9b3fd384b4 to your computer and use it in GitHub Desktop.
Maybe Monad in Python 3
#!/usr/bin/env python3
import functools
from typing import TypeVar, Generic, Callable, Optional
T = TypeVar('T')
class Maybe(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
def __repr__(self) -> str:
return f"Maybe({self.value})"
def get(self) -> T:
return self.value
def with_maybe(transform: Callable[[T], T]) -> Callable:
@functools.wraps(transform)
def wrapper(input_: Maybe[T]) -> Maybe[T]:
if input_.value is None:
return Maybe(None)
return Maybe(transform(input_.value))
return wrapper
@with_maybe
def add_one(x: int) -> int:
return x + 1
@with_maybe
def multiply_by_two(x: int) -> int:
return x * 2
n0: str = input("Please enter an integer: ")
print(f"n0 = '{n0}'")
n0_ = None if n0 == "" else int(n0)
n1: Maybe[Optional[int]] = Maybe(n0_)
print(f"n1 = {n1}")
n2: Maybe[Optional[int]] = add_one(n1)
print(f"n2 = {n2}")
n3: Maybe[Optional[int]] = multiply_by_two(n2)
print(n3.value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment