tail recursive function and wrapper function

4 visualizzazioni (ultimi 30 giorni)
Samantha Steele
Samantha Steele il 20 Set 2011
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

Risposte (2)

Walter Roberson
Walter Roberson il 21 Set 2011
MATLAB has no special support for tail recursion, just for recursion.

Ramon Villamangca
Ramon Villamangca il 20 Giu 2021
Modificato: Ramon Villamangca il 20 Giu 2021
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

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by