Determining if a card is in the same pile as another card

  • Thread starter Thread starter Potatochip911
  • Start date Start date
AI Thread Summary
A Prolog predicate is needed to determine if two cards are in the same pile based on their placement defined by facts like above(x,y) and below(x,y). The user has created a test pile but encounters infinite loops when attempting to implement the recursive predicate samePile(X, Y). The recursion fails because it repeatedly calls itself without reaching a base case, particularly when querying samePile(p,d). The discussion highlights the equivalence of above and below relationships, suggesting that only one should be stored as a fact to simplify the logic. The challenge lies in effectively traversing the pile in both directions without causing infinite recursion.
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 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.
 
Back
Top