Re:PHP: why GOTO instead of recursion?
by toast0 on Tuesday September 23, 2014 @01:26PM
(#8356582)
Some languages don't have loops, so you have to use tail recursion. Sometimes, tail recursion is more clear or concise than a loop:
Erlang:
fib(1) -> 1;
fib(2) -> 1;
fib(N) when N > 2 -> fib(fib(1), fib(2), N - 2).
fib(_A, B, 0) -> B;
fib(A, B, N) when N > 0 -> fib(B, A + B, N - 1).
C:
int fib(int count) {
int a = 1, b =1;
while (--count >= 2) {
int next = a + b;
a = b;
b = next;
}
return b;
}
Notes: Erlang version will crash if given value is less than 1; C version will just return 1 for anything outside of accepted range. Erlang integers become large integers automatically, C integers will overflow. If you prefer fib(0) == 0, you can adjust it, with more work for C, because I cheated the initial conditions/bounds check.
(I shrunk the C code a bit more than originally written, and it's now pretty similar in length... I guess it's about the same... which is the point :)
Erlang:
C: Notes: Erlang version will crash if given value is less than 1; C version will just return 1 for anything outside of accepted range. Erlang integers become large integers automatically, C integers will overflow. If you prefer fib(0) == 0, you can adjust it, with more work for C, because I cheated the initial conditions/bounds check.(I shrunk the C code a bit more than originally written, and it's now pretty similar in length... I guess it's about the same... which is the point :)