2 ms·
> Recursion is also producing results that are "wrong answers" Not true. If you share your copy of: answer = sum [1..10] One viewer might see: answ
by mrkeen 4y ago
> Recursion is also producing results that are "wrong answers"
Not true. If you share your copy of:
answer = sum [1..10]
One viewer might see:
answer = 3 + sum [3..10]
and another viewer might see:
answer = 6 + sum [4..10].
They may be "partial results", but they are correct and equal to each other. This is different from one viewer seeing 3 and another viewer seeing 6.
"But can't you just hide the partial result until it's ready?"
Sure. Get rid of class fields and getters(). I'm happy to. Are you?
- mpweiher 4y agoYou tend to not put temporary results of loops in instance variables, but in local variables. Which aren't visible externally at all. And yes, if you do have that exceptional case of a complex algorithm that needs to store partial results in ivars as they are required by different methods and inconvenient to pass around individually, those ivars tend to not be exposed. In fact, you'd more likely create a separate context object that you pass around, so also not visible externally.
- mrkeen 4y ago> You tend to not put temporary results of loops in instance variables, but in local variables. Which aren't visible externally at all. Cool! Then it follows: If a result is not temporary, then it can be immutable. Properly immutable, not just final. If a result is temporary, then it is not to be visibly external at all. Not as a field, and not via any getter. I could live with that.
- mpweiher 4y agoThat doesn't follow. Objects do (much) more than implement algorithms in loops. In fact, I'd say that if you're doing algorithms as objects, you're almost certainly Holding it Wrong™. Algorithms tend to be perfectly fine contained in a method of an object.
- Joker_vD 4y agoHave you heard about the concept of "loop invariant"? s = 0 i = 0 // Invariant: before and after every iteration, s is equal to sum of [0..i] // End condition: i == n while i != n: s += i i += 1 // Here, i == n and so s is a sum of [0..n] because the invariant still holds That's how loops were supposed to be thought about (and written) since the 70ies, and it's more or less equivalent to induction which is what you're supposed to use when you think about recursive functions.