next up previous contents index
Next: Input/Output Up: Programming Concepts Previous: Cartesian   Contents   Index

Subsections

Ordered pairs

Description

This concept creates ordered pairs of entries from a list. Each combination where the first element occurs in the input list before the second element is created exactly once.

The result is a list of terms pair(X, Y) where X and Y are elements of the input list L.

Parameters

L
a list
K
a free variable, will be bound to a list

Schema

:-mode ordered_pairs(+,-).
ordered_pairs(L,K):-
        ordered_pairs_lp(L,[],K).

ordered_pairs_lp([],L,L).
ordered_pairs_lp([H|T],In,Out):-
        ordered_pairs_lp2(H,T,In,In1),
        ordered_pairs_lp(T,In1,Out).

ordered_pairs_lp2(H,[],L,L).
ordered_pairs_lp2(H,[A|A1],In,Out):-
        ordered_pairs_lp2(H,A1,[pair(H,A)|In],Out).

Comments

The second and third argument of ordered_pairs_lp and the third and fourth argument of ordered_pairs_lp2 serve as an accumulator to collect the results.

This concept can also be implemented with nested do loops. The recursive version seems more natural.

ordered_pairs(L,K):-
        (fromto(L,[El|Rest],Rest,[_]),
         fromto(K,TPairs,RPairs,[]) do
            (foreach(R,Rest),
             param(El),
             fromto(TPairs,[pair(El,R)|Pairs],Pairs,RPairs) do
                true
            )
        ).


Warwick Harvey
2004-08-07