I am using Block
inside the definition of some recursive functions.
If the Block definitions use short variable names, like {s = First[param], r = Rest[param]}
, an infinite recursion occurs when param
contains one of the symbols s
or r
.
Using tortured local symbols names minimizes this risk, but
- it makes code unreadable,
- it does not prevent the collision risk, but only minimizes it.
How to deal with local variable assignment without any collision risk?
Substitution rules and Modules have their own problems with recursive functions, which is why I use Blocks, but it's maybe the wrong tool.
Edit: There is no good reason not to use Module, except if one wants to locally modify the recursion limit, it seems. For my part, I was just confused, and I should just use Module.
Module
? I think it would be the right tool here. $\endgroup$Block
is almost never a good solution. So what's wrong withModule
? It seems to me thatModule
is the way to go here, but you didn't explain what the problem is with it. $\endgroup$$RecursionLimit
- it is all to easy to crash the kernel resetting this value, and I would not trust the code which does that. $\endgroup$Block
and cannot useModule
, put the local variable symbols in a private context:Begin["myfun`"]; myfun[x_] := Block[{s=1}, x+s]; End[]
. Nowmyfun[s]
will returns+1
as expected. $\endgroup$