Skip to content

Instantly share code, notes, and snippets.

@simrit1
Forked from cafuneandchill/maybe_monad.py
Created July 27, 2022 06:46
Show Gist options
  • Save simrit1/fe0ace75d195a9a9440953fac737f640 to your computer and use it in GitHub Desktop.
Save simrit1/fe0ace75d195a9a9440953fac737f640 to your computer and use it in GitHub Desktop.
Maybe Monad in Python 3
#!/usr/bin/env python3
from typing import TypeVar, Generic, NoReturn, Callable
import functools
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}'")
n1: Maybe[int] = Maybe(None if n0 == "" else int(n0))
print(f"n1 = {n1}")
n2: Maybe[int] = add_one(n1)
print(f"n2 = {n2}")
n3: Maybe[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