Last active
November 24, 2022 11:54
-
-
Save candlerb/e38b02977a1f288e49ecb28f752fb642 to your computer and use it in GitHub Desktop.
Value chaining, a.k.a. continuations
This file contains 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
# Add syntactic sugar so that values flow along a "pipeline": | |
# A >> B >> C | |
# becomes C(B(A)) | |
# | |
# To do this in Python we need to wrap the value in its own class | |
class Value: | |
def __init__(self, value): | |
self.value = value | |
# `value >> func` calls `func(unwrapped-value)` | |
def __rshift__(self, other): | |
return other(self.value) | |
def f(x): | |
return Value(x*x) | |
def g(x): | |
return Value(2*x) | |
def h(x): | |
return Value(1+x) | |
result = Value(4) >> f >> g >> h | |
print(result.value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment