Comment by ndriscoll

12 hours ago

  def reduce(acc, f): 
    for v in self:
      acc = f(acc, v)
    return acc

The current acc goes out of scope each time you call f. There's no shared reference (assuming f doesn't sneak store it elsewhere, which for string combining, f should just be `return a+b`?).

The binding for acc in the reduce call is still active during the f call, which means there are at least two references to acc.

  • Why is it still active? Even an interpreter with no lookahead could see that it goes out of scope immediately when f returns (it gets shadowed on that line), so as long as there's no guarantee about when finalizers get called, it should be able to mark it dead inside of reduce as soon as it's passed to f. Like move semantics here should be a general pattern for optimization, no?