5 ms·
> Off by one errors can't happen in the functional version. No? Not only can they happen, but I'd argue that it's easier for them to occur when using `reduce`
by carussell 9y ago
> Off by one errors can't happen in the functional version.
No? Not only can they happen, but I'd argue that it's easier for them to occur when using `reduce`, because you have to remember the initializer. Omitting it has no effect in the given example, but the given example is contrived. It's not rare to be dealing with something more complex than a list of numbers, so let's try that instead.
Let's say your items are a list of nodes. You want to sum their payloads to determine their aggregate cost. And, like jasonkostempski[1], you see `map` as superfluous. You've got this. You write:
nodes.reduce((sum, x) => sum + x.value)
Uh-oh. Now the fact that there is no initializer does affect the result.
1. https://news.ycombinator.com/item?id=15867033 https://news.ycombinator.com/item?id=15867033
- thethirdone 9y ago> No? Not only can they happen, but I'd argue that it's easier for them to occur when using `reduce`, because you have to remember the initializer. I would say that's not an off by one error. Its a similar scale and type of error, but not the same.
- dvt 9y agoIt's much more insidious than an off-by-one error in a for-loop - the initializer is hidden!
- spdionis 9y agoUnless you use a language that actually enforces you to pass required parameters to a function call.
- carussell 9y ago... which still wouldn't fix this problem, because the initializer is not a required parameter. It's allowed to be omitted by design, to signify that the first element shall be skipped and never passed as the second arg to the callback—or to put it another way, instead of being called once for each element, it's meant to handle the gaps between elements.
- carussell 9y agoEr, the single-parameter version of reduce differs from the two-parameter version in that the semantics are changed to literally skip the callback invocation where the first element gets passed as x. Instead of being called n times, it gets called n-1 times. It's one of the most clear-cut manifestations of fences vs posts—the quintessential off-by-one problem.