尾递归浅谈

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>

  

posted @ 2012-11-08 23:48  caochao88  阅读(313)  评论(0编辑  收藏  举报