# ==========================================================
# This is an example of a functor
# ==========================================================
#-----------------------------------------------------------
# ---- pipeline class
# ---- this pipeline of functions work on a single integer.
# ---- When the integer is modified a new pipeline
# ---- is created and passed to the next function.
# ----------------------------------------------------------
class Pipeline():
# ---- initialize pipeline
def __init__(self,value):
self.value = value
# ---- returns a new (modified) pipeline object
def bind(self,func):
return Pipeline(func(self.value))
# ----------------------------------------------------------
# ---- main
# ----------------------------------------------------------
if __name__ == '__main__':
def add_1(x): # simple work function
if x == None: return None
return x + 1
def multiply_3(x): # simple work function
if x == None: return None
return x * 3
def subtract_2(x): # simple work function
if x == None: return None
return x - 2
# ---- pipeline: -2 -> *3 -> +1 -> v
# ---- order of operations left to right
x = 4
pipe = Pipeline(x)
v = pipe.bind(subtract_2) \
.bind(multiply_3) \
.bind(add_1).value
print(f'v={v} type={type(v)}')
# ---- reverse the order of operations
pipe = Pipeline(x)
v = pipe.bind(add_1) \
.bind(multiply_3) \
.bind(subtract_2).value
print(f'v={v} type={type(v)}')