#/usr/bin/env python3
def fold(function, value, iterable, /, *, reverse = None):
it = (reversed if reverse else iter)(iterable)
args = lambda value, element: (value, element) if reverse == False else \
(element, value)
for element in it:
value = function(*args(value, element))
return value
if __name__ == '__main__':
from operator import add
z = 'z'
print(f'{fold(add, z, ["a", "b", "c", "d"])}\n{fold(add, z, ["a", "b", "c", "d"], reverse = True)}\n{fold(add, z, ["a", "b", "c", "d"], reverse = False)}')
Iy91c3IvYmluL2VudiBweXRob24zCgpkZWYgZm9sZChmdW5jdGlvbiwgdmFsdWUsIGl0ZXJhYmxlLCAvLCAqLCByZXZlcnNlID0gTm9uZSk6CiAgICBpdCA9IChyZXZlcnNlZCBpZiByZXZlcnNlIGVsc2UgaXRlcikoaXRlcmFibGUpCiAgICBhcmdzID0gbGFtYmRhIHZhbHVlLCBlbGVtZW50OiAodmFsdWUsIGVsZW1lbnQpIGlmIHJldmVyc2UgPT0gRmFsc2UgZWxzZSBcCiAgICAgICAgICAgKGVsZW1lbnQsIHZhbHVlKQogICAgZm9yIGVsZW1lbnQgaW4gaXQ6CiAgICAgICAgdmFsdWUgPSBmdW5jdGlvbigqYXJncyh2YWx1ZSwgZWxlbWVudCkpCiAgICByZXR1cm4gdmFsdWUKCmlmIF9fbmFtZV9fID09ICdfX21haW5fXyc6CiAgICBmcm9tIG9wZXJhdG9yIGltcG9ydCBhZGQKICAgIHogPSAneicKICAgIHByaW50KGYne2ZvbGQoYWRkLCB6LCBbImEiLCAiYiIsICJjIiwgImQiXSl9XG57Zm9sZChhZGQsIHosIFsiYSIsICJiIiwgImMiLCAiZCJdLCByZXZlcnNlID0gVHJ1ZSl9XG57Zm9sZChhZGQsIHosIFsiYSIsICJiIiwgImMiLCAiZCJdLCByZXZlcnNlID0gRmFsc2UpfScpCg==