Post #4332493
2026-08-01 09:41 UTC
Replies (3)
-
@ireneista@adhd.irenes.space 2026-08-01 09:46
@simontatham@hachyderm.io the situation where we use recursion the most personally is traversing an AST. maybe that could work as an example?
-
@slava@mathstodon.xyz 2026-08-01 09:56
@simontatham@hachyderm.io “the only sensible thing to do is write a recursive function, containing _one_ of those for loops; give it a parameter to control the recursion depth, and at the deepest level it calls f with the list it built up.” An n-tuple with elements drawn from a finite set of k elements is just a base-k integer with n digits, isn’t it? So an easy way to generate all such n-tuples is to start with the first such tuple and repeatedly increment it by one until you carry the last digit. Seems a bit simpler than recursion
-
@darkling@mstdn.social 2026-08-01 10:19
@simontatham@hachyderm.io You can do this simply and non-recursively with something like: result = values[0] for v in values[1:]: result = cross_product(result, v) def cross_product(xs, ys): result=[] for x in xs: for y in ys: result.append(x+[y]) return result But the recursive version is probably a bit more obvious.