-
-
Save milesrout/2ea0dbe72084e10fddca4d9019ea73a7 to your computer and use it in GitHub Desktop.
Javascript's foreach in 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
accumulate = lambda t: lambda f: lambda *a, **k: t(f(*a, **k)) | |
@accumulate(list) | |
def foreach(iterable, func): | |
for i, x in enumerate(iterable): | |
yield func(x, i) | |
mylist = list(chr(n) for n in range(65, 75)) | |
foreach(mylist, lambda x, i: print('{} => {}'.format(i, x))) | |
# 0 => A | |
# 1 => B | |
# 2 => C | |
# 3 => D | |
# 4 => E | |
# 5 => F | |
# 6 => G | |
# 7 => H | |
# 8 => I | |
# 9 => J | |
print(foreach(range(10), lambda n, _: n ** 2)) | |
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment