Prolog代码结果未存储问题:如何将加法结果存入fresult?
fresult Predicate Let's break down what's wrong with your current code and how to fix it to store the addition result in the fresult predicate.
What's Wrong in the Original Code
- Your
fresult(P, Q) :- P+Q.rule doesn't actually store or return the result. In Prolog, writingP+Qalone just evaluates the expression but doesn't bind it to a variable—so the result is lost immediately. - When you call
write(fresult)at the end, you're just printing the atomfresult, not the calculated addition result.
Solution 1: Store Result as a Dynamic Fact
If you want to persist the result in the fresult predicate (so you can query it later), we'll use assertz/1 to add a dynamic fact to the Prolog database. Here's the corrected code:
gresult:- write('enter first number'), nl, read(P), nl, write('enter second number'), nl, read(Q), nl, R is P + Q, % Calculate the sum and bind it to variable R write('addition result is '), write(R), nl, assertz(fresult(P, Q, R)), % Store the result as a fresult/3 fact write('Result saved! Query fresult('), write(P), write(', '), write(Q), write(', R). to retrieve it.'). % Optional: Define fresult/3 to query stored results fresult(P, Q, R) :- fact(fresult(P, Q, R)).
How It Works:
R is P + Q: This is the correct way to perform arithmetic in Prolog—is/2evaluates the right-hand expression and binds the result to the left-hand variable.assertz(fresult(P, Q, R)): This adds a new fact likefresult(2, 3, 5)to the database. You can later run queries likefresult(X, Y, Z).to see all stored results, orfresult(2, 3, R).to get the sum of 2 and 3.
Solution 2: Use fresult as a Calculation Predicate (No Storage)
If you just want fresult to compute the sum without storing it long-term, adjust the predicate to take a third argument for the result:
% Define fresult to calculate P+Q and return R fresult(P, Q, R) :- R is P + Q. gresult:- write('enter first number'), nl, read(P), nl, write('enter second number'), nl, read(Q), nl, fresult(P, Q, R), % Get the sum into R write('addition result is '), write(R), nl.
This version uses fresult as a function-like predicate to compute the sum, but doesn't store the result permanently.
Testing the Fix
Run gresult. in your Prolog interpreter, enter two numbers, and you'll see the result printed and (in Solution 1) stored. You can verify the storage by querying fresult(X, Y, Z). afterwards—you'll see all the sums you've calculated so far.
内容的提问来源于stack exchange,提问作者Hasibul Islam Santo

