home *** CD-ROM | disk | FTP | other *** search
- Although Turbo Prolog is a descriptive computer language, it is
- often desirable to repeat a process more than once. This is
- known as creating a loop. Implementing a loop in Turbo Prolog is
- challenging to most novice users.
-
- There are two main ways to create a loop in Turbo Prolog,
- recursively and iteratively. The first way, recursion, can be
- the most straightforward, but due to the demands made on RAM, the
- iterative approach is also a desirable technique.
-
- In showing how loops are implemented, we will construct two short
- programs which count up to 100. The first program, the recursive
- approach, is similar to a FOR loop implemented in other computer
- languages.
-
- /* RECURSIVE COUNTER */
- PREDICATES
- count(integer)
- CLAUSES
- count(100) :- !.
- count(X) :- Y = X + 1 ,
- write(Y), nl , /* body of loop goes here */
- count(Y).
- GOAL
- count(0).
- /* END */
-
- Of course, there are many variations to this small program. If
- recursion is still a mystery to you, follow this program through
- in the trace mode.
-
- The next program shows a more complicated loop, yet the result is
- the same as the previous program. This program works on a
- repeat/fail technique, and therefore can be used when available
- memory becomes a consideration.
- /* ITERATIVE LOOP */
- DATABASE
- counter(integer)
- PREDICATES
- my_retract(dbasedom)
- count
- repeat
- CLAUSES
- count :- asserta( count(0) ) , fail. /* initialize counter */
- count :- repeat ,
- count(X) ,
- Y = X + 1 ,
- my_retract( count(X) ) ,
- asserta( count(Y) ) ,
- write(Y), nl ,
- Y = 100.
-
- my_retract(X) :- retract(X), !. /* deterministic retract */
-
- repeat. repeat :- repeat.
- GOAL
- count.
- /* END */
-
- Here, the body of the loop is placed between the repeat and the
- failing condition. Notice that the failing condition succeeds
- when the looping process is complete.
-
- The most important thing to remember when coding such a loop is
- to be sure that all the calls made between the repeat and the
- failing condition are deterministic. Remember, when a call fails
- in Turbo Prolog, the backtracking mechanism returns to the last
- non-deterministic call made and attempts to REDO that call.
-
- In the iterative loop design, it is very important that
- processing returns back to the top of the loop before attempting
- another cycle. For this reason, we have coded a deterministic
- version of the predicate retract(), (the built-in predicate
- retract() is non-deterministic by definition).
-