Skip to content

Instantly share code, notes, and snippets.

@GoldsteinE
Created May 5, 2020 19:47
Show Gist options
  • Save GoldsteinE/bfcedd0a638d79edf88510ef18161175 to your computer and use it in GitHub Desktop.
Save GoldsteinE/bfcedd0a638d79edf88510ef18161175 to your computer and use it in GitHub Desktop.
# pylint: disable=all
from __future__ import annotations
from typing import Callable, Generic, List, Optional, TypeVar, Union
T = TypeVar('T')
S = TypeVar('S')
R = TypeVar('R')
Transform = Callable[[T], S]
def identity(x: T) -> T:
return x
def compose(left: Transform[T, S], right: Transform[S, R]) -> Transform[T, R]:
def result(val: T) -> R:
return right(left(val))
return result
class Val(Generic[T, S]):
def __init__(self, func: Transform[T, S]) -> None:
self.func: Transform[T, S] = func
@classmethod
def start(cls) -> Val[float, float]:
return Val(identity)
def compose(self, nxt: Transform[S, R]) -> Val[T, R]:
return Val(compose(self.func, nxt))
def __add__(self: Val[float, float], other: float) -> Val[float, float]:
return self.compose(lambda x: x + other)
def __mul__(self: Val[float, float], other: float) -> Val[float, float]:
return self.compose(lambda x: x * other)
def __lt__(self: Val[float, float], other: float) -> Val[float, bool]:
return self.compose(lambda x: x < other)
# ... define all other operators here
class Vec(List[T]):
def map(self, transform: Union[Transform[T, S], Val[T, S]]) -> Vec[S]:
if isinstance(transform, Val):
return self.map(transform.func)
return Vec(map(transform, self))
X = Val.start()
if __name__ == '__main__':
vec = Vec([1., 2., 3.])
print(vec.map(X * 2))
print(vec.map(X < 2.))
print(vec.map(X * 2 < 4.))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment