I think it may be one of those things you have to see in order to understand.
I think it may be one of those things you have to see in order to understand.
With a very basic concrete example:
x = 7
x = x + 3
x = x / 2
Vs
x = 7
x1 = x + 3
x2 = x1 / 2
Reordering the first will have no error, but you'll get the wrong result. The second will produce an error if you try to reorder the statements.
Another way to look at it is that in the first example, the 3rd calculation doesn't have "x" as a dependency but rather "x in the state where addition has already been completed" (i.e. it's 3 different x's that all share the same name). Doing single assignment is just making this explicit.
> You should strive to never reassign or update a variable outside of true iterative calculations in loops.
If you want a completely immutable setup for this, you'd likely have to use a recursive function. This pattern is well supported and optimized in immutable languages like the ML family, but is not super practical in a standard imperative language. Something like
def sum(l):
if not l: return 0
return l[0] + sum(l[1:])
Of course this is also mostly insensitive to ordering guarantees (the compiler would be fine with the last line being `return l[-1] + sum(l[:-1])`), but immutability can remain useful in cases like this to ensure no concurrent mutation of a given object, for instance.For example you can modify sum such that it doesn't depend on itself, but it depends on a function, which it will receive as argument (and it will be itself).
Something like:
def sum_(f, l):
if not l: return 0
return l[0] + f(f, l[1:])
def runreq(f, *args):
return f(f, *args)
print(runreq(sum_, [1,2,3]))[0]: https://docs.python.org/3/whatsnew/3.14.html#a-new-type-of-i...
Updating one or more variables in a loop naturally maps to reduce with the updated variable(s) being (in the case of more than one being fields of) the accumulator object.
You're using recursion. `runreq()` calls `sum_()` which calls `sum()` in `return l[0] + f(f, l[1:])`, where `f` is `sum()`
def sum_(f, l):
if not l: return 0
return l[0] + f(f, l[1:])
def runreq(f, *args):
return f(f, *args)
print(995,runreq(sum_, range(1,995)))
print(1000,runreq(sum_, range(1,1000)))
when run with python3.11 gives me this output: 995 494515
Traceback (most recent call last):
File "/tmp/sum.py", line 9, in <module>
print(1000,runreq(sum_, range(1,1000)))
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/sum.py", line 6, in runreq
return f(f, *args)
^^^^^^^^^^^
File "/tmp/sum.py", line 3, in sum_
return l[0] + f(f, l[1:])
^^^^^^^^^^^
File "/tmp/sum.py", line 3, in sum_
return l[0] + f(f, l[1:])
^^^^^^^^^^^
File "/tmp/sum.py", line 3, in sum_
return l[0] + f(f, l[1:])
^^^^^^^^^^^
[Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded in comparison
A RecursionError seems to indicate there must have been recursion, no?