简体   繁体   中英

Store a result to a variable in prolog?

parent(max,alex).

?- parent(max,alex).
"true."
?- parent(max,jack).
"false."

?- X = parent(max,jack), write(X). // Why X != false?
"X = parent(max, jack)."

How to store to X answer from query "parent(max,jack)"(true or false)?

What you're trying to do is find out if parent(max, jack) is going to succeed. Usually in Prolog you would do something like this:

foo :-
  parent(max, jack),
  % if you make it here, the predicate is true
  ...
foo :-
  % since you're here, the predicate is false

However, this may be obscured by whatever else you're doing. If you want to be more explicit about it, you can use the conditional construct:

foo :-
  (parent(max, jack) 
     -> % true case
      ; % else case)

If you want X to be true if this is true, you can do this:

foo :-
  (parent(max, jack) -> X = true ; X = false),
  ...

Prolog doesn't have functions . It has predicates . They do not do the same thing.

So X = parent(max,jack). isn't a function call to parent that returns the result of parent(max,jack) into X .

parent(max,jack) is a predicate that inquires whether the relation parent(max, jack) is true. It is either true or false, and prolog will tell you whether it is true or false.

When you enter the above expression, X = parent(max,jack) , you are using the =/2 predicate in prolog. That's the unification operator. That means "what's on the left is unified with what's on the right of the =". If there are variables on either side, prolog will attempt to instantiate the variables to make the expression TRUE. In this case, the statement is TRUE if prolog instantiates X with the expression parent(max,jack) . Thus, you get the result:

X = parent(max,jack).

If you want to query the parent relationship between max and an unknown, X , do this:

parent(max, X).

Then prolog will seek values of X to make the expression true, and you will get:

X = alex.

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