I am working on my very first Prolog assignment, and on recursive problems, I cannot seem to stop overflowing the stack. It's like an addiction; I don't know how to stop.
Let me give you an example. I want to create a function that determines if an object, Y, is a part of another object, X. Here is the database I am working with:
% Parts Database
has(bicycle,wheel,2).
has(bicycle,handlebar,1).
has(bicycle,brake,2).
has(wheel,hub,1).
has(wheel,spoke,32).
has(bicycle,frame,1).
has(car,steering_wheel,1).
has(car,stereo,1).
has(car,tires,4).
From here, I want to write a function partof(X,Y)
that returns true if Y is a part of X. This is what I currently have:
% Determines if Y is a part of X
partof(X,Y) :-
has(X,Y,_).
partof(X,Y) :-
partof(X,Z),
partof(Z,Y).
This works for all true
queries, but overflows the stack instead of returning false.
For example:
?- partof(wheel, spoke).
true ;
ERROR: Out of local stack
?- partof(bicycle, spoke).
true ;
ERROR: Out of local stack
?- partof(wheel, X).
X = hub ;
X = spoke ;
ERROR: Out of local stack
I know you are all thinking to yourselves, "This dumb idiot, doesn't know what a base case is. Doesn't know how to pull out of recursion." Well, I don't blame you. I feel dumb. Some patient guidance would be very helpful, though. Thanks in advance!