Last active
June 25, 2024 12:24
-
-
Save hanshoglund/a3c95e1ec955cc596d9d4a142d1a5a69 to your computer and use it in GitHub Desktop.
adts2.py
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
# mypy 1.8.0, python 3.12 | |
# supports recursion + generics unlike (https://gist.github.com/hanshoglund/cd4302f2c1e07370649b5983bead320e) | |
# OTOH, no exhaustive checks in match clasuses. And issues like: https://gist.github.com/hanshoglund/d255b3a9ff0a07cf7504a3b4313d6d7c | |
# | |
# Note: if we ONLY use frozen dataclasses as here, we have Eq,Ord,Show,Hashable, so the need for ad-hoc polymorphism is greatly reduced | |
from typing import Generic, TypeVar, final | |
from typing import Callable | |
from dataclasses import dataclass | |
T = TypeVar("T") | |
class List(Generic[T]): ... | |
@final | |
@dataclass(frozen=True) | |
class Cons(List[T]): | |
car: T | |
cdr: List[T] | |
@final | |
class Nil(List): ... | |
T1 = TypeVar("T1") | |
S = TypeVar("S") | |
def foldr(fn: Callable[[S, T1], T1], acc: T1, lst: List[S]) -> T1: | |
match lst: | |
case Nil(): | |
return acc | |
case Cons(x, xs): | |
return fn(x, foldr(fn, acc, xs)) | |
assert False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment