3 ms·
One way that would make that particular example clearer is to convert the multiplication from an infix operation to a function call: return n == 0 ? 1 : n * fa
by kenjackson 16y ago
One way that would make that particular example clearer is to convert the multiplication from an infix operation to a function call:
return n == 0 ? 1 : n * fac(n -1);
becomes
return n == 0 ? 1 : multiply(n, fac(n -1);
This makes it a fair bit clearer, IMO.
- deleted 16y ago[deleted]
- kenjackson 16y ago[no longer applies to the comment]
- barrkel 16y agoI suspect a better approach is to make expected tail recursion a language feature, and have the compiler emit an error if the returned expression is not in fact valid for a tail call. Imagine if it were 'treturn' or something. It's not something that bites people who have been around this mulberry bush before, but I think it can very likely catch problems that novices have, thinking they're writing an O(1) space solution but actually using O(n) stack.
- eru 16y agoOK. But then, even if somebody is using `return', and its tail-recursive, it should be optimized. (`return' should just not raise an error, if it's not tail-recursice.)