Created
June 29, 2017 00:25
-
-
Save malcolmgreaves/b02010db05645b667cae1231832bfa39 to your computer and use it in GitHub Desktop.
Fold left and fold right for Python.
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
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