Skip to content

Instantly share code, notes, and snippets.

@lispyclouds
Last active October 5, 2024 10:10
Show Gist options
  • Save lispyclouds/23e653a9b54a95078321af5999d8caa4 to your computer and use it in GitHub Desktop.
Save lispyclouds/23e653a9b54a95078321af5999d8caa4 to your computer and use it in GitHub Desktop.
Pythonic M
from dataclasses import dataclass
from typing import Callable, Protocol, Self, TypeVar
T = TypeVar("T", covariant=True)
class Result(Protocol[T]):
def then(self, f: Callable[[T], Self]) -> Self: ...
@dataclass
class Success(Result[T]):
value: T
def then(self, f: Callable[[T], Self]) -> Self:
return f(self.value)
@dataclass
class Failure(Result[T]):
error: Exception
def then(self, f: Callable[[T], Self]) -> Self:
return self
def read_and_add(prev: int = 0) -> Result[int]:
try:
return Success(prev + int(input("Enter a number: ")))
except KeyboardInterrupt:
return Failure(Exception("Cancelled"))
except Exception as e:
return Failure(e)
if __name__ == "__main__":
result = read_and_add().then(read_and_add).then(read_and_add)
match (result):
case Success(value):
print(f"Sum: {value}")
case Failure(error):
print(f"Error: {error}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment