Skip to content

Instantly share code, notes, and snippets.

@candlerb
Last active November 24, 2022 11:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save candlerb/e38b02977a1f288e49ecb28f752fb642 to your computer and use it in GitHub Desktop.
Save candlerb/e38b02977a1f288e49ecb28f752fb642 to your computer and use it in GitHub Desktop.
Value chaining, a.k.a. continuations
# 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