尾递归浅谈
erlang:
bump(L) -> bump_acc(L, []). bump_acc([], Acc) -> reverse(Acc); bump_acc([H|T], Acc) -> bump_acc(T, [H+1|Acc]). reverse(L) -> reverse_acc(L, []). reverse_acc([], Acc) -> Acc; reverse_acc([H|T], Acc) -> reverse_acc(T, [H|Acc]).
c#:
public static int FactorialRecursively(int n) { return FactorialContinuation(n-1, r => n*r); } public static int FactorialContinuation(int n, Func<int, int> continuation) { if(n == 0) return continuation(1); return FactorialContinuation(n-1, r => continuation(n*r)); } //calc !10 FactorialContinuation(10, x => x);
推演:
FactorialRecursively(3)
-> FactorialContinuation(2, r => 3*r);
-> FactorialContinuation(1, r => 3*2*r);
-> FactorialContinuation(0, r => 3*2*1*r);
-> 3*2*1
javascript:
<html> <script type="text/javascript"> function factorialRecursively(n) { var func = function(r) { return n * r; } return factorialContinuation(n-1, func) } function factorialContinuation(n, func) { if(n == 0) return func(1); var con = function(r) { return func(n*r); } return factorialContinuation(n-1, con) } var func = function(x) { return x; } var test0 = factorialRecursively(5); document.write("test0 val:" + test0); document.write("<br/>"); var test = factorialContinuation(5, func) document.write("test val:" + test); </script> </html>
作者:
caochao
邮箱: caochao88@gmail.com
出处: http://www.cnblogs.com/tudas
本文版权归作者和博客园共有,欢迎转载,未经作者同意须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
邮箱: caochao88@gmail.com
出处: http://www.cnblogs.com/tudas
本文版权归作者和博客园共有,欢迎转载,未经作者同意须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。