Is_a predicate definition in prolog?

I am trying to determine the inheritance check predicate is_a/2in Prolog, but so far all my tests have failed.

The predicate is_a(X, Y)should return true when Y is a superclass of X. For example:

object(bare).
object(mammal).
object(animal).
object(bird).
is_a(bare, mammal).
is_a(mammal, animal).
is_a(bird, animal).
is_a(X, Y):- <definition goes here>.

The definition should look like the following query returns true:

?- is_a(bare, animal).
true.

I tried to define it in an obvious way, but I was stuck in endless loops:

is_a(X, Y):- X\==Y, object(X), object(Y), object(Z), is_a(X, Z), is_a(Z, Y).

Any suggestions?

+3
source share
2 answers

One way to avoid an infinite loop is to add a predicate that shows “direct” inheritance (not transitive), namely direct/2. Then you can write something like this:

object(bare).
object(mammal).
object(animal).
object(bird).

direct(bare, mammal).
direct(mammal, animal).
direct(bird, animal).

isa(X, Y) :- object(X), object(Y), direct(X, Y).
isa(X, Y) :- object(X), object(Y), object(Z), direct(X, Z), isa(Z, Y).

:

?- findall(X, isa(X, animal), L).
   L = [mammal,bird,bare] ? ;
   no

, , .

+5

-

is_a(X, X).
is_a(X, Y) :- X \== Y, is_a_1(X, Z), is_a(Z, Y).
is_a_1(bear, mammal).
is_a_1(mammal, animal).
is_a_1(bird, animal).

: , electrologos3, , .

+2

Source: https://habr.com/ru/post/1728674/


All Articles