Quote:
|
Originally Posted by titaniumdecoy
I understand how the accumulator function works, but how come the curr variable has to be a list? Why doesn't the following work?
|
In a nutshell, it's because Python's syntax does not distinguish between assignment and declaration. Instead, Python has to infer when a variable should be defined from the context; as a rule, it declares a new variable if no variable with the same name exists in the local scope.
Remember that "curr += inc" is equivalent to "curr = curr + inc", so it's an assignment. Because it's the first such assignment in the local scope, it's also a declaration. Thus, curr is first defined, and assigned the value "curr + inc". Unfortunately, because curr is defined before the assignment is evaluated, the curr in "curr + inc" refers to the variable you've just defined. Since you haven't assigned this curr a value yet, an error arises.
This problem can be circumvented by an explicit declaration keyword; let's call it "var". Then, the code would look like:
def make_acc(start=0):
"""accumulator generator """
var curr = start
def acc(inc):
curr += inc
return curr
return acc However, because Python does not have this keyword, instead relying on implicit declarations, we instead have to use the next best thing; a mutable variable. The most common mutable variable is a list
def make_acc(start=0):
"""accumulator generator """
curr = [start]
def acc(inc):
curr[0] += inc
return curr[0]
return acc This was pointed out to me by a fellow on Slashdot. He argued that Perl was more suited toward a more functional style of programming than Python (or even Ruby), because Perl supports explicit declarations (via
my). I have to admit that he's right there. Subfunctions and scoping is one thing Perl does a bit better than its successors.