Monday, January 19, 2009

Ch2, Ex9

(a)Sum1 in kernel language:

proc {Sum1 N ?R}
local T in
T = N==0
if T then R=0
else
local L in
L = {Sum1 N-1}
R = N + L
end
end
end
end

As recursive call is not the last call, hence its not tail-recursive.

Sum2 in kernel language:

proc {Sum2 N S ?R}
local T in
T = N==0
if T then R=S
else
{sum2 N-1 N+S}
end
end
end

As there is just one recursive call and its the last, hence its tail-recursive.

(b)
In case of Sum1 stack size will grow linearly while in case of Sum2 it remains constant. Store size grows linearly in both the cases but several variables in the store are unreachable when Sum2 is executing.
TODO: hand execute the calls

(c)On my system {Sum2 100000000 0} was successfully able to calculate the result(5000000050000000) and {Sum1 100000000} just hanged (probably due to unavailability of enough memory as Sum1 is not tail recursive)

No comments:

Post a Comment