The questions are:
- Do generators break the functional programming paradigm? Why or why not?
- If yes, can generators be used in functional programming and how?
Consider the following:
function * downCounter(maxValue) {
yield maxValue;
yield * downCounter(maxValue > 0 ? maxValue - 1 : 0);
}
let counter = downCounter(26);
counter.next().value; // 26
counter.next().value; // 25
// ...etc
The downCounter
method appears stateless. As well, calling downCounter
with the same input, will always result in the same output. However, at the same time, calling next()
does not produce consistent results.
I'm unsure whether or not generators break the functional programming paradigm because in this example counter
is a generator object and so calling next()
would produce the same results as another generator object created with the exact same maxValue
.
As well, calling someCollection[3]
on an array would always return the fourth element. Similarily, calling next()
four times on a generator object would also always return the fourth element.
For more context, these questions were raise while working on a programming kata. The person that answered the question, raised the question whether or not generators could be used in functional programming and whether or not they hold state.