4 ms·
Something that I only realised the other day which made me feel kinda embarrassed: in ruby, the reduce method is called inject. For years I've been doing MapRe
by JonnieCache 16y ago
Something that I only realised the other day which made me feel kinda embarrassed: in ruby, the reduce method is called inject.
For years I've been doing MapReduce functions, without realising it. MapReduce was in my mental pile of "genius things that cleverer people than me do, must be looked into when there is time."
For info on inject: http://blog.jayfields.com/2008/03/ruby-inject.html http://blog.jayfields.com/2008/03/ruby-inject.html
- revorad 16y agoA nice relevant post from raganwald - http://weblog.raganwald.com/2008/02/1100inject.html http://weblog.raganwald.com/2008/02/1100inject.html
- raganwald 16y agoThanks you for your nice words. I would have suggested this one, although it has been discussed Ad Nauseum on HN in the past: http://weblog.raganwald.com/2007/03/why-why-functional-programming-matters.html http://weblog.raganwald.com/2007/03/why-why-functional-progr...
- SandB0x 16y agoIn Ruby the reduce method is also called reduce: [1,2,3].inject{|s,i| s += i} => 6 [1,2,3].reduce{|s,i| s += i} => 6
- JonnieCache 16y agoReduce is an alias for inject, and depending on which template you use to generate the docs, method aliases are not given the same prominence as full methods. Some templates simply say "this method is also known as..." underneath the original method in a tiny font. If it were the other way around, and inject was an alias for reduce, I think there would be a lot less confused rubyists.
- DanielRibeiro 16y agoI've wrote about these ancient ways of great languages a while ago: http://metaphysicaldeveloper.wordpress.com/2009/05/02/closures-collections-and-some-functional-programming/ http://metaphysicaldeveloper.wordpress.com/2009/05/02/closur...
- Peaker 16y agoWhat would it do on an empty list? It should probably take an argument for the empty case... What is the history behind the name "inject" here?
- kejadlen 16y agoBy default, inject uses the first element of the array as the argument, so it would use nil on an empty list. It optionally takes an argument to kick off the process.
- kragen 16y agoThe name comes from Smalltalk. I imagine that the idea is that you're "injecting" an operator between items in the list: 1 2 3 4 becomes 1 + 2 + 3 + 4.
- radiowave 16y agoMost likely Ruby takes the name inject from Smalltalk. (Smalltalk also uses 'collect' for map, 'select' for filter, 'reject' for an inverse filter.)
- kgo 16y agoThank you for pointing out the history! The names inject, collect, select, and reject drive me crazy for some reason. Maybe it's because they rhyme. But every time I saw them, I wondered why Matz made these up instead of using map/filter/reduce. At least now I know.