Guide to Prolog Programming
© Roman Barták, 1998
In this section, we
present a generalized list processor which is capable to do various
list operations depending on the definition of functions e and f.
This program is a simplified version of general list processor from
R.A. O'Keefe's book The Craft of Prolog, MIT, 1990.
list_processor(,R):-e(R). list_processor([H|T],R):- list_processor(T,TR), f(H,TR,R).
If we define the functions e and f in a following way:
e(0). f(A,B,C):-C is A+B.
the resulting program sums elements in the list.
The following definition:
e(0/0). f(X,A/B,A1/B1):-A1 is A+X, B1 is B+1.
can be used to compute average of elements of the given list.
The same schema can be used to sort elements in the list or to generate permutations. First we definie functions e and f:
If the procedure insert is defined in a following way:
insert(X,,[X]). insert(X,[Y|T],[X,Y|T]):-X<=Y. insert(X,[Y|T],[Y|NT]):-X>Y,insert(X,T,NT).
the resulting program sorts list.
If the following definition of insert is used:
the resulting program generates permutations of given list successively.
Designed and maintained by Roman Barták