-
-
Save lispyclouds/23e653a9b54a95078321af5999d8caa4 to your computer and use it in GitHub Desktop.
Pythonic M
This file contains hidden or 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
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