Thursday, February 5, 2009

Ch6, Ex2

declare
fun {SumList Xs}
C={NewCell 0}
fun {Recurse Xs}
case Xs of X|Xr then
C := @C + X
{Recurse Xr}
else @C
end
end
in
{Recurse Xs}
end
%Test
{Browse {SumList [1 2 3 4]}} %10

Another version which is slightly more readable but works only for sequential computation model, it breaks if multiple threads use it(Why? Hint: All threads can change the contents in the cell)
declare SumList
local C={NewCell 0}
in
fun {SumList Xs}
case Xs of X|Xr then
C := @C + X
{SumList Xr}
else Y=@C in
C := 0
Y
end
end
end

%Code that shows that this fails with concurrent model
%MakeList creates a list of 1s of length N
declare
fun {MakeList N}
fun {Iter X N}
if N>0 then {Iter 1|X N-1}
else X
end
end
in
{Iter nil N}
end

%Test
%should print 100000
{Browse {SumList {MakeList 100000}}}
%Both of these should also print 100000
%but they mostly don't
thread {Browse {SumList {MakeList 100000}}} end
thread {Browse {SumList {MakeList 100000}}} end

No comments:

Post a Comment