Last active
March 15, 2017 01:31
-
-
Save louisswarren/813c5238742cb3d44438f736f3fca3cd 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
Javascript benefits from ignoring unneeded arguments, so that if you don't care about indices you can just not accept one in your lambda.
Python benefits from not being javascript.