4 ms·
You don't have to use recursion, that is, you don't need language support for it. Having first class (named) functions is enough. For example you can modify su
by bmacho 1y ago
You don't have to use recursion, that is, you don't need language support for it. Having first class (named) functions is enough.
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]))
- DemocracyFTW2 1y ago> You don't have to use recursion You're using recursion. `runreq()` calls `sum_()` which calls `sum()` in `return l[0] + f(f, l[1:])`, where `f` is `sum()`
- bmacho 1y ago> You're using recursion. No, see GP. > `runreq()` calls `sum_()` which calls `sum()` in `return l[0] + f(f, l[1:])`, where `f` is `sum()` Also no, see GP.
- DemocracyFTW2 1y agoI am too stupid to understand this. This: 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?