tail recursive function and wrapper function
4 次查看(过去 30 天)
显示 更早的评论
Ok so it program a tail-recursive function to calculate A. and i need to add a wrapper function..
A=1-(1/2)+(1/3)-(1/4)+(1/5)-(1/6).... A is calculated when the last item is smaller than 10^-3
0 个评论
回答(2 个)
Walter Roberson
2011-9-21
MATLAB has no special support for tail recursion, just for recursion.
0 个评论
Ramon Villamangca
2021-6-20
编辑:Ramon Villamangca
2021-6-20
The question is not about whether Matlab supports tail recursion. The question is to make a tail recursive function and wrapper function that presumably would enable to tail recursion support. Can we do that?
Lets see the tail recursive function first:
function a = asum(lim)
a = arec(lim-1,0,1);
end
function a = arec(lim,acc,cur)
if cur > lim
a = acc;
elseif mod(cur,2)
a = arec(lim,acc+1/cur,cur+1);
else
a = arec(lim,acc-1/cur,cur+1);
end
end
Now, the limit given (1/10^3) is so small that the above function will work without any wrapper function:
>> asum(10^3)
ans =
0.6936
But if we increase the limit to say, 1/10^6, we will run to "out of memory" error:
>> asum(1000000)
Out of memory. The likely cause is an infinite recursion within the program.
Error in asum>arec (line 9)
a = arec(lim,acc+1/cur,cur+1);
For this we need a wrapper function. One way is to use a "trampoline" wrapper. We need to modify the recursive function as follows:
function a = asum(lim)
a = trampoline(arec(lim-1,0,1));
end
function a = arec(lim,acc,cur)
if cur > lim
a = acc;
elseif mod(cur,2)
a = @() arec(lim,acc+1/cur,cur+1);
else
a = @() arec(lim,acc-1/cur,cur+1);
end
end
With this one we will not run out of memory:
>> asum(1000000)
ans =
0.6931
The trampoline wrapper function looks like this:
function t = trampoline(f)
%TRAMPOLINE wrapper function to convert tail-recursive functions to loops
% Usage: trampoline(f), where f is a tail-recursive function
while isa(f,'function_handle')
f = f();
end
t = f;
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!