Reputation: 35
Suppose you have a bunch of boxes inside other boxes, i.e.
inBox(a,b).
inBox(b,c).
inBox(c,d).
inBox(x,y) meansbox x is in box y. Now I want to write a method to determine if one box is inside of another box, e.g. insideBox(a,d) = true since a is inside b, which is inside c, which is inside d. So it appears to be a naturally recursive problem and my attempt at solving it fails to initialize my variable to "move one box up":
insideBox(X, Y) :- inBox(X, Y), inBox(X, Z), insideBox(Z,Y).
The logic is to first check the base case of whether or not box X is currently inside box Y, if not then call inBox(X, Z) to get a value for which box X is in and then recall the recursive method. I have tried looking at the trace but can't reason what is going on:
| ?- insideBox(a,d).
1 1 Call: insideBox(a,d) ? c
2 2 Call: inBox(a,d) ? c
2 2 Fail: inBox(a,d) ? c
1 1 Fail: insideBox(a,d) ? c
I've tried other stuff like Z is inBox(X, _) for setting the variable Z but this hasn't worked either and I have no clue how Z is ending up with the value of a.
Upvotes: 1
Views: 103
Reputation: 117037
Try this:
?- insideBox(a,d).
inBox(a,b).
inBox(b,c).
inBox(c,d).
insideBox(X,Z) :- inBox(X,Z).
insideBox(X,Z) :- inBox(X,Y), insideBox(Y,Z).
Just a side-note: be careful with the terms you use. You don't "assign" variables, instead you "unify" them. Also you're not writing "methods", you're writing "predicates".
Upvotes: 2