Prolog predicate for checking if two cards are in the same pile

  • Thread starter Thread starter Potatochip911
  • Start date Start date
Join the discussion
Registration is free. Start your own thread to ask a follow-up.
2 replies · 2K views
Potatochip911
Messages
317
Reaction score
3

Homework Statement


Write a predicate to determine if two cards are in the same pile. The placement of the cards is given as facts above(x,y), x is above y, or below(x,y), x is below y. I'm supposed to do this using Prolog which is a first-order logic language.

Homework Equations



The Attempt at a Solution


I made an arbitrary pile of cards to test my method, the facts for this pile I'm using are.
Code:
below(c,b).
below(d,c).
above(a,b).
above(p,a).
So from top to bottom my pile is p->a->b->c->d. The problem I'm running into when writing the recursive samePile(X, Y) predicate is I keep running into infinite loops. I'm not sure how to write the recursion so that it will exhaust all options going up the pile and then exhaust all options going down the pile. This is the code I currently have:

Code:
samePile(X, Y) :- above(X, Y), !.
samePile(X, Y) :- above(Y, X), !.
samePile(X, Y) :- below(X, Y), !.
samePile(X, Y) :- below(Y, X), !.
samePile(X, Y) :- above(X, Z), samePile(Z, Y), !; above(Z, X), samePile(Z, Y), !.
samePile(X, Y) :- below(Z, X), samePile(Z, Y), !; below(X, Z), samePile(Z, Y), !.

One example query that results in an infinite loop is samePile(p,d) which will alternate between calling samePile(a,d) and samePile(b, d) since a is stored as above(a, b) so whenever we get to samePile(b, d) we will just go back up to samePile(a,d). I am completely lost at this point as to how I can make a recursion that travels through the entire pile.
 
Physics news on Phys.org
above(a,b) == below(b,a)? If yes, get rid of one.
You can just start from card A and go in both directions as far as I see.
 
  • Like
Likes   Reactions: Potatochip911
mfb said:
above(a,b) == below(b,a)? If yes, get rid of one.
You can just start from card A and go in both directions as far as I see.

While the two statements are equivalent only one will be stored as a fact. A pile could be expressed as a bunch of above(x,y) facts, under(x,y) facts, or a combination of both so it seems necessary to include both.