Thursday, February 5, 2009

Ch6, Ex3

I could not find a way to have encapsulated sum count without using explicit state and also had to change the arguments in SumList. The difficulty is that count variable needs to change with each call to SumList but in declarative model we can not change a variable value once its bound,so we have to keep track of change by creating new variables and binding them to new values.
This is my new SumList
declare
fun {SumList Xs S CountS CountSnext}
CurrentCount Cs
in
CountS = access(CurrentCount)|assign(CurrentCount+1)|Cs
%{Browse currentcount} {Browse CurrentCount}
case Xs
of nil then
CountSnext = Cs
S
[] X|Xr then
{SumList Xr X+S Cs CountSnext}
end
end
fun {MakeState Init}
proc {Loop S V}
case S of access(X)|S2 then
X=V {Loop S2 V}
[] assign(X)|S2 then
{Loop S2 X}
else skip end
end
S
in
thread {Loop S Init} end
S
end

%usage, notice how the state is wind up in C0, C1,...
%calling SumList the first time
declare C0 S={MakeState 0}
{Browse {SumList [1 2 3 4] 0 S C0}}

%Accessing current count
declare C1 in
local X in
C0=access(X)|C1
{Browse X} %5
end

%Calling SumList again
declare C2 in
{Browse {SumList [1 2] 0 C1 C2}}

%Accessing current count
declare C3 in
local X in
C2=access(X)|C3
{Browse X} %8
end

Clearly this version is not readable, not easy to use(because counting functionality is not encapsulated) as caller needs to keep track of variables.. hence declarative model alone is not expressive enough to give this functionality

No comments:

Post a Comment