简体   繁体   中英

Trouble with defining rules in Prolog

married(man, woman).
married(B, A) :- 
  married(A, B)

If B is married to A , A is married to B .
I understand that writing it as I have creates a loop, but I don't know how to prevent this.

parent(Parent, Child) :- 
    parent(married(Parent, Spouse), Child).

I am also unable to do something like this.

If Parent is the parent of Child :-
the spouse of Parent is the parent of Child .

Make two separate predicates. First you define a predicate that lists facts:

married_fact(philip, elisabeth).
married_fact(william, kate).

married(X, Y) :-
    married_fact(, ).
married(X, Y) :-
    married_fact(, ).

I am also unable to do something like this:

If Parent is the parent of Child :- the spouse of Parent is the parent of Child .

The syntax parent(married(Parent, Spouse), Child). does not make much sense, since married(Parent, Spouse) is here a functor. Even if Prolog would see it as a predicate, a predicate does not "return" anything. A predicate is either true or false.

You can define a parent_fact/2 predicate:

parent_fact(phillip, charles).

and then define a predicate:

parent(Parent, Child) :-
    parent_fact(Parent, Child).
parent(Parent, Child) :-
    married(Parent, Spouse),
    parent_fact(Spouse, Child).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM