1
votes

I'm trying to solve:

Given facts such as

  • Bob is taller than Mike.
  • Mike is taller than Jim
  • Jim is taller than George

Write a recursive program that will determine that Bob's height is greater than George's.

My solution so far is:

taller_than(bob, mike).
taller_than(mike, jim).
taller_than(jim, george).

taller_than(X,Y):-
    taller_than(X, Z),
    taller_than(Z, Y).

It returns True as expected, but then I reach the stack limit. I'm guessing I need a base case, but I'm not sure what it would be? Is my solution otherwise correct?

1

1 Answers

3
votes

Oh so close.

Your main problem is that you have facts taller_than/2 and predicates taller_than/2 with the same signature. This even caught me off guard when I gave it an initial test run. You need to change the name of either the fact or the predicate. For this the name of the predicate is changed.

As you noted you need a base case and had you done the name change I think you would have figured this out also.

taller_than_rule(X,Y) :-
    taller_than(X,Y).
taller_than_rule(X,Y) :-
    taller_than(X, Z),
    taller_than_rule(Z, Y).

Example run:

?- taller_than_rule(bob,Who).
Who = mike ;
Who = jim ;
Who = george ;
false.