0

I am very new to Prolog programming. Any help is greatly appreciated. I have the following program,

bigger(elephant, horse).
bigger(horse, donkey).
bigger(donkey, dog).
bigger(donkey, monkey).

is_bigger(X, Y) :- bigger(X, Y).
is_bigger(X, Y) :- is_bigger(Z, Y), bigger(X,Z).

On running the query,

?- is_bigger(A, donkey)

I get the following output,

A = horse ;
A = elephant ;
ERROR: Out of local stack

While I do somewhat understand how A = horse and A = elephant, I am having a difficult time understanding why it's recursing infinitely (I used the builtin trace trace predicate but couldn't understand it after A = elephant).

Thank you.

false
  • 10,264
  • 13
  • 101
  • 209

1 Answers1

0
is_bigger(X, Y) :- is_bigger(Z, Y), bigger(X,Z).

The above line is the one causing the out of local stack message. You're calling "is_bigger" again which calls "is_bigger" again and so on, recursively


Your input: is_bigger(A, donkey)

First, you want to find something that is bigger than the donkey or/and something that is bigger than the thing that's bigger than the donkey.

Therefore:

is_bigger(X, Y) :- bigger(Z, Y), bigger(X,Z).

Why?

Y binds to donkey.

Z bind to horse.

As a last step, you're looking for bigger(X, horse)

Does that make sense?

  • I think the recursion is the whole point, since we want to be able to detect chains longer than 2, i.e. something that is bigger than something that is bigger than ... that is bigger than a donkey. If we also had `bigger(whale, elephant).` then your approach would not agree that `is_bigger(whale, donkey)`. – Nate Eldredge Sep 20 '20 at 17:12
  • In that case: is_bigger(X, Y) :- bigger(Z, Y), is_bigger(X,Z). –  Sep 20 '20 at 17:22
  • The reason it doesn't work when you put is_bigger first, is because it will keep looping trying to find is_bigger(Z,Y). But if you put it last, it will have found all animals in bigger(Z,Y) already, which then can be recursed/matched through in Z in the last is_bigger(X,Z). –  Sep 20 '20 at 17:30
  • 1
    @programmingwat could you update your answer with the proper recursive solution so we can upvote it? – Isabelle Newbie Sep 20 '20 at 18:34