Last active
September 5, 2023 14:25
-
-
Save llimllib/cb687339523b13d949f89daa2e9264ac to your computer and use it in GitHub Desktop.
in response to https://mathstodon.xyz/@vez/111012730223951046
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 collections import UserList | |
from functools import partial | |
from operator import add | |
# a class that allows a subclass to declare a function to use to handle all protocols | |
class CustomApplyList(UserList): | |
def __init__(self, f, args): | |
super().__init__(args) | |
self.f = f | |
def __add__(self, n): | |
self.data = self.f(partial(add, n), self.data) | |
return self | |
# XXX: implement other operator protocols here | |
def __call__(self, g): | |
self.data = self.f(g, self.data) | |
return self | |
# which lets you define a class like this, with a function that describes how to apply functions to itself | |
class Mapper(CustomApplyList): | |
def __init__(self, args): | |
super().__init__(lambda data, f: list(map(data, f)), args) |
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
In [8]: m = Mapper([1,2,3]) | |
In [9]: m + 1 | |
Out[9]: Mapper([2, 3, 4]) | |
In [10]: m(lambda x: x ** 2) | |
Out[10]: Mapper([4, 9, 16]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment