Next: Filter
Up: Programming Concepts
Previous: Iteration on array
  Contents
  Index
Subsections
This next concept is used to perform some transformation on each element of a list and to create a list of the transformed elements. At the end, both lists will have the same length, and the elements match, i.e. the first element of the second list is the transformed first element of the first list.
This concept uses the foreach keyword in two different ways. The first is used to scan an existing list L, the second is used to construct a list K as the result of the operation.
- L
- a list
- K
- a free variable, will be bound to a list
:-mode transformation(+,-).
transformation(L,K):-
(foreach(X,L),
foreach(Y,K) do
q(X,Y)
).
In the code above we cannot see that list L is an input and list K is an output. This can only be deduced from the calling pattern or from the mode declaration.
The example takes a list of router_mib_data terms and builds a list of temporary t/2 terms where the second argument consists of router_mib terms.
:-mode convert_to_router_mib(+,-,-).
convert_to_router_mib(L,K,Router):-
(foreach(router_mib_data with
[router:Router,
time:Time,
tcp_segm_in:A,
tcp_segm_out:B,
udp_datagram_in:C,
udp_datagram_out:D],L),
foreach(t(Time,router_mib with
[tcp_segm_in:A,
tcp_segm_out:B,
udp_datagram_in:C,
udp_datagram_out:D]),K),
param(Router) do
true
).
In this example the transformation is completely handled by matching arguments in the foreach statements. We use the predicate true for an empty loop body.
Figuring out what is happening with the variable Router is left as an exercise for the advanced reader.
Next: Filter
Up: Programming Concepts
Previous: Iteration on array
  Contents
  Index
Warwick Harvey
2004-08-07