Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Created June 29, 2017 00:25
Show Gist options
  • Save malcolmgreaves/b02010db05645b667cae1231832bfa39 to your computer and use it in GitHub Desktop.
Save malcolmgreaves/b02010db05645b667cae1231832bfa39 to your computer and use it in GitHub Desktop.
Fold left and fold right for Python.
def foldl(zero, combine, elements):
if callable(zero):
result = zero()
else:
result = zero
for x in elements:
result = combine(result, x)
return result
def foldr(zero, combine, elements):
return foldl(zero, combine, reversed(elements))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment