Skip to content

Instantly share code, notes, and snippets.

@llimllib
Last active September 5, 2023 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save llimllib/cb687339523b13d949f89daa2e9264ac to your computer and use it in GitHub Desktop.
Save llimllib/cb687339523b13d949f89daa2e9264ac to your computer and use it in GitHub Desktop.
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)
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