foreach with accumulators

The base foreach is not suitable for computing aggregates. B-Prolog extends it to allow accumulators. The extended foreach takes the form:


aa aaa aaa aaa aaa aaa aaa 
		 		 foreach(E1 in D1, $\ldots$, En in Dn, LocalVars,Accs,Goal) 
or


aa aaa aaa aaa aaa aaa aaa 
		 		 foreach(E1 in D1, $\ldots$, En in Dn, Accs,LocalVars,Goal) 
where Accs is an accumulator or a list of accumulators. The ordering of LocalVars and Accs is not important, since the types are checked at runtime.

One form of an accumulator is ac(AC,Init), where AC is a variable and Init is the initial value for the accumulator before the loop starts. In Goal, recurrences can be used to specify how the value of the accumulator in the previous iteration, denoted as AC^0, is related to the value of the accumulator in the current iteration, denoted as AC^1. Let's use Goal(ACi,ACi+1) to denote an instance of Goal in which AC^0 is replaced with a new variable ACi, AC^1 is replaced with another new variable ACi+1, and all local variables are renamed. Assume that the loop stops after n iterations. Then this foreach indicates the following sequence of goals:



aa aaa aaa aaa aaa aaa aaa 
		 		  AC0 = Init, 

Goal(AC0,AC1),
Goal(AC1,AC2),
$\ldots$,
Goal(ACn-1,ACn),
AC=ACn



Subsections
Neng-Fa Zhou 2013-01-25