ABC
ABC

Reputation: 47

list of lists- recursive pairs prolog

how can I put all the pairs in a one list?

I have -

pair([H|T], [H,E]) :- member(E, T).
pair([_|T], P) :- pair(T, P).

and I want the answer will be a list of pairs.

so I try -

listPairs([],[Res1]):-
      Res1=[].
listPairs(L,[Res2]):-
    L=[H|T],
    append(pair([H|T],[Res2]),listPairs(T,[Res2])).

but I miss something of the lists.. because it is not compile.

Upvotes: 0

Views: 982

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476750

I don't really see what you aim to do with append/2. You can definitely not put goals that should be called in the append/3 because in that case, they will be seen as functors.

You can however easily use the findall/3 predicate which is implemented in nearly all Prolog systems (well at least all I have seen that are actively used):

listPairs(L,Pairs) :-
    findall(Pair,pair(L,Pair),Pairs).

findall/3 works as follows:

findall(Format,Goal,List).

Here you specify a Goal (here pair(L,Pair)) and Prolog will call the Goal. Each time the Goal succeed, Prolog will suspend the interpreter and add en element formatted as Format to the List. When the Goal fails, the list of all Formats is returned.

If I run the query, I get:

?- listPairs([1,a,2,'5'],Pairs).
Pairs = [[1, a], [1, 2], [1, '5'], [a, 2], [a, '5'], [2, '5']].

Note that L must be grounded (as list, meaning without uninstantiated tail, an uninstantiated element is fine), since otherwise the number of pair/2 elements that you will generate is infinite and thus you will run out of global stack (or memory in general).

Upvotes: 3

Related Questions