简体   繁体   中英

How do you store a result to a variable in prolog?

I can't seem to find a resource that describes how one could store the result of a query so that I can use it for the next.

What about just obtaining a boolean value from the query?

A predicate does not have a return value. What you could do to simulate a return value is add another argument:

add_numbers(X,Y):-
   Return is X+Y.

would become

add_numbers(X,Y,Return):-
   Return is X+Y.

and when you call it, you will use a variable:

?- add_numbers(4,3,Result).
Result = 7.

note that you could also call it like this:

?- add_numbers(4,3,7).
true

but also:

?- add_numbers(4,3,8).
false

but it is not possible to do the call add_numbers(X,2,7 because we have used arithmetic. however, a lot of predicates can be used however you want.

for example, prolog has a built-in predicate called append/3 . normally you would use it like this:

?-append([1,2],[3,4],X).
X=[1,2,3,4]

but you can also use it like this:

?- append(X,Y,[1,2,3]).
X = [],
Y = [1, 2, 3] ;
X = [1],
Y = [2, 3] ;
X = [1, 2],
Y = [3] ;
X = [1, 2, 3],
Y = []

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