Simple Counter

The following program is a simple binary counter.

declare bit/2 key 1.
declare max/1 key 0.
declare pos/1 key 0.
declare num/1 key 0.

initialize(M) <-
     create num(0) sc
     create max(M) sc
     create pos(0) sc
     with [M] while (pos(N), N < M)
         do (create bit(N,0) sc N2 is N+1 sc set pos(N2)) sc
     set pos(0).

zero <- while bit(N,1) do set bit(N,0).

incr <-
     set pos(0) sc
     while (pos(N), bit(N,1))
         do (set bit(N,0) sc N2 is N+1 sc set pos(N2)) sc
     pos(N) sc
     max(M) sc
     if (N < M) then set bit(N,1).

count <- while bit(N,0) do incr.

count(M) <-
     set num(0) sc
     with [M] while (num(N), N < M)
         do (incr sc N2 is N+1 sc set num(N2)).

The tuple bit(X,Y) stores the value Y of bit X. The value Y is either 0 or 1.
The tuples max/1, pos/1, num/1 can be consider as a temperary variable to store the number of bits, the current position of the pointer, and the value of the counter, respectively.

Having loaded the above program, a 5 bit counter, for instance, can be initialized by executing initialize(5). The predicate zero can reset the counter to 0 and the predicate incr increments the counter by 1. Finally, the predicate count increments the value counter to its maximum value stepwise and count(M) increments the counter from 0 to M stepwise.

Back to the main page