CTM book (p. 262)

Aurélien Campéas aurelien.campeas at logilab.fr
Mon Feb 26 13:40:25 CET 2007


On Sun, Feb 25, 2007 at 08:14:00PM -0600, Craig Ugoretz wrote:
> Hello,
> 
> The following code is from the CTM book, Ch. 4 on declarative concurrency,
> p.262:
> 
> declare
> proc {DGenerate N Xs}
>   case Xs of X|Xr then
>      X=N
>      {DGenerate N+1 Xr}
>   end
> end
> 
> fun {DSum ?Xs A Limit}
>   if Limit>0 then
>      X|Xr=Xs
>   in
>      {DSum Xr A+X Limit-1}
>   else A end
> end
> 
> local Xs S in
>   thread {DGenerate 0 Xs} end
>   thread S={DSum Xs 0 4} end
> end

I wonder if this code can be considered (by newbies to dataflow
programming knowing a little Python) a bit more readable, if only
because some important operations hidden beneath Oz's syntax are shown
in full light (non-logic variables in small letters):

        def generate(n, Xs):
            wait(Xs)
            Xr = newvar()
            unify((n, Xr), Xs)
            generate(n+1, Xr)

        def sum(Xs, a, limit):
            if limit > 0:
                X, Xr = newvar(), newvar()
                unify((X, Xr), Xs)
                return sum(Xr, a+X, limit-1)
            else:
                return a

        Xs = newvar()
        S = future(sum, Xs, 0, 10)
        future(generate, 0, Xs)
        print S

Note that this isn't pseudo-code, it actually runs. Unfortunately, it
leaves the generator thread hanging forever, stuck on the unbound
Xs. So you'd need to :

 unify(Xs, None) # for instance

before returning a in sum, so as to allow the generator to die with a
unification error.


> 
> The generator only supplies values to the sum function when it needs them.
> Notice that the two are in different threads and appear to share a dataflow
> variable Xs.  I have been trying to understand this code, and I do not
> understand, after running the code in the debugger, how the system knows
> that Xs is a list variable.  This is considering that Xs is never
> initialized to a value initially.  I am sure that I am thinking in
> sequential, not concurrent terms.  The line that especially troubles me is
> X|Xr = Xs in the sum function, with the X and the Xr on the left.  Can
> anyone tell me how the dataflow variables work such that the generator and
> the summer work together?

Oz syntax was definitively a bit too compact for my beginner's taste,
too.

Regards,
Aurélien.


More information about the mozart-users mailing list