Created
March 22, 2016 17:00
-
-
Save hunan-rostomyan/68cbc5e9854d6a2559a1 to your computer and use it in GitHub Desktop.
Using reduce to define map [JS, 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
// In a language with arrays, `reduce` can be used | |
// to accumulate arrays and thus can be used to | |
// define array-producing operators like `map`. | |
Array.prototype.map = function(fn) { | |
return this.reduce(function(sum, cur) { | |
return sum.concat(fn(cur)); | |
}, []); | |
}; |
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
# In a language with lists, `reduce` can be used | |
# to accumulate lists and thus can be used to | |
# define list-producing operators like `map`. | |
def map(fn, lst): | |
return reduce(lambda sum, cur: sum + [fn(cur)], lst, []) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment