TuanDT
TuanDT

Reputation: 1677

Appending a list in Prolog

I'm just starting logic programming(in Prolog), and it's very different from procedure/OO. Please help out:

male(a).
male(b).
male(c).

female(x).
female(y).

append([],X,X).
append([X|Y],Z,[X|W]):- append(Y,Z,W).

partners(X,Y):- male(X), female(Y).

I'm trying to write a predicate getAllPartners(MyList, Output) that outputs a list including all possible combinations of partners. I don't mind having 0s in the list, but if anyone figure out a way of not having 0s in the output list, that'll be awesome. Here's my 'buggy, crappy' code, please help:

getAllPartners(MyList, Output):-
append([],0,MyList),
partners(X,Y),
append(MyList,X,Output),
append(Output,Y,MyList),
append(MyList,0,Output).

Upvotes: 0

Views: 472

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

Instead of manually appending such lists, Prolog has a builtin findall:

getAllPartners(L) :-
  findall((M,F),(male(M),female(F)),L).

Or even more compact:

getAllPartners(L) :-
  findall((M,F),partners(M,F),L).

When you call:

getAllPartners(L).

It will respond with:

L = [ (a, x), (a, y), (b, x), (b, y), (c, x), (c, y)].

You can generate your list manually, as well, but the problem with your approach is that partners(X,Y) will always bind with the same people first. Your list is thus [ a, x, 0, a, x, 0, a, x, 0, ...]. Another problem you should resolve is the fact that you append "lists" and not a "list" with an "element".

Upvotes: 0

Related Questions