next up previous contents
Next: Reconstructing Lists Up: Program Patterns Previous: Return a Result

Return a Result ---Having Processed All Elements

We now deal with a very common task: taking a list of elements and transforming each element into a new element (this can be seen as a mapping). The schema for this is:

 
 process_all( Info,[],[]).

process_all( Info,[H1T1],[H2T2]):-

process_one( Info,H1,H2),

process_all( Info,T1,T2).

where process_one/1 takes Info and H1 as input and outputs H2

The reading for this is that the result of transforming all the elements in the empty list is the empty list otherwise, transform the head of the list and then transform the rest of the list.
The second clause can be rewritten to:
 
process_all( Info,[H1T1],Ans):-

process_one( Info,H1,H2),

process_all( Info,T1,T2),

Ans = [H2T2].

Understanding the way in which this program works is quite difficult.

An example program is one that takes a list of integers and `triples' each of them. The goal triple([1,12,7],X would result in X=[3,36,21]. We assume the mode of mode triple(+,-).

 
triple([],[]).

triple([H1T1],[H2T2]):-

H2 is 3*H1,

triple(T1,T2).

This has the reading that the two arguments lie in the relation that the head of the second argument is 3 times that of the head of the first argument and the tails lie in the same relation. The declarative reading is easier to construct than exploring the way in which a goal is executed.



Paul Brna
Mon May 24 20:14:48 BST 1999