Last active
September 4, 2022 22:24
-
-
Save theteachr/b3bbe6b180b6a6af19feb5b7988d29c6 to your computer and use it in GitHub Desktop.
Playing with overload ops to get fp features in Python
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
class BitShiftFunc: | |
def __init__(self, f): | |
self.f = f | |
def __lshift__(self, rhs): | |
return self.f(rhs) | |
def __rrshift__(self, lhs): | |
return self.f(lhs) | |
def __getattr__(self, f): | |
@BitShiftFunc | |
def composed(x): | |
return self.f(globals()[f](x)) | |
return composed | |
def __mul__(self, times): | |
@BitShiftFunc | |
def runner(x): | |
start = x | |
for _ in range(times): | |
start = self.f(start) | |
return start | |
return runner | |
def __call__(self, *args, **kwds): | |
return self.f(*args, **kwds) | |
@BitShiftFunc | |
def square(x): | |
return x * x | |
@BitShiftFunc | |
def inc(x): | |
return x + 1 | |
def cube(x): | |
return x ** 3 | |
@BitShiftFunc | |
def curried_map(f): | |
return BitShiftFunc(lambda lst: list(map(f, lst))) | |
def main(): | |
print(BitShiftFunc(cube) << 3) # 27 | |
print(BitShiftFunc(len) << 'Hello') # 5 | |
print(square(2)) # 4 | |
print(square << 2) # 4 | |
print(square . inc << 2) # 9 | |
print(inc . square << 2) # 5 | |
print(inc . inc . square . inc << 2) # 11 | |
print((inc . inc . square . inc * 2) << 2) # 146 | |
print((inc * 4) << 2) # 6 | |
print(2 >> inc) # 3 | |
print([8, 2] >> (curried_map << square)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment