Skip to content

Instantly share code, notes, and snippets.

@nerodono
Last active August 17, 2024 12:10
Show Gist options
  • Save nerodono/18595b7bc946a986f97b426c0edf7d50 to your computer and use it in GitHub Desktop.
Save nerodono/18595b7bc946a986f97b426c0edf7d50 to your computer and use it in GitHub Desktop.
import dataclasses as dtc
@dtc.dataclass
class Ok:
ok: "Nigger"
@dtc.dataclass
class Err:
err: "Gay"
def then(lhs, rhs):
def impl(req, next):
return lhs(req, lambda x: rhs(x, next))
return impl
def bind(lhs):
def impl(req, next):
if isinstance(req, Ok):
return lhs(req.ok, next)
return next(req)
return impl
def identity(x):
return x
def ratio(req, next):
if req == 0.0:
return next(Err("division by zero"))
return next(Ok(1.0 / req))
def apply(h, f):
return lambda x: h(x, f)
num_identity = apply(then(ratio, bind(ratio)), identity)
print(num_identity(10))
@la5tway
Copy link

la5tway commented Aug 16, 2024

import dataclasses as dtc
from typing import Callable as C
from typing import Generic, TypeVar

T = TypeVar("T")


@dtc.dataclass
class Ok(Generic[T]):
    ok: T


@dtc.dataclass
class Err:
    err: str = "Gay"


R = Ok[T] | Err
F = C[[R[T]], R[T]]


def then(lhs: C[[T, F[T]], R[T]], rhs: C[[R[T], F[T]], R[T]]) -> C[[T, F[T]], R[T]]:
    def impl(req: T, next: F[T]) -> R[T]:
        return lhs(req, lambda x: rhs(x, next))

    return impl


def bind(lhs: C[[T, F[T]], R[T]]) -> C[[R[T], F[T]], R[T]]:
    def result(req: R[T], next: F[T]) -> R[T]:
        if isinstance(req, Ok):
            return lhs(req.ok, next)
        return next(req)

    return result


def identity(x: T) -> T:
    return x


def ratio(req: float, next: F[float]) -> R[float]:
    if req == 0.0:
        return Err("division by zero")
    return next(Ok(1.0 / req))


def apply(h: C[[T, F[T]], R[T]], f: F[T]) -> C[[T], R[T]]:
    return lambda x: h(x, f)


num_identity = apply(then(ratio, bind(ratio)), identity)  # (variable) def num_identity(float) -> (Ok[float] | Err)
print(num_identity(10))  # Ok(ok=10.0)

mypy: Success: no issues found in 1 source file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment