% demonstration of how backtracking in Prolog acts like a co-routine. square(X,Y):- Y is X*X. % The only way to store intermediate results in Prolog is to file them in the data base. summer_setup:-asserta(sum_is_now(0)), !. % This is the worker predicate - it pulls the total out of the data base(retract) % and then adds it to the current X. Ut then puts the NewSum in the data base. summer(X):-retract(sum_is_now(S),_), !, NewS is S + X, asserta(sum_is_now(NewS)). % gen(X) generates three values, one after another... gen(1). gen(2). gen(3). trace [gen,summer, square,sum_is_now]! % How to sum the gen-erated data: set up, then gen and accumulate. % Run as a query - and each 'y' input adds in the next one. dosum:- summer_setup, gen(I), summer(I), sum_is_now(S). dosumsqr:- summer_setup, gen(I), J is I*I, summer(J), sum_is_now(S). % Here is an alternate generator getem(I):-repeat, prin("Input a number and a period > "),read(T),I is T. % sum input data... suminput:- summer_setup, getem(I), summer(I), sum_is_now(S).