You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prolog代码结果未存储问题:如何将加法结果存入fresult?

Fixing Prolog Result Storage in 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, writing P+Q alone 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 atom fresult, 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:

  1. R is P + Q: This is the correct way to perform arithmetic in Prolog—is/2 evaluates the right-hand expression and binds the result to the left-hand variable.
  2. assertz(fresult(P, Q, R)): This adds a new fact like fresult(2, 3, 5) to the database. You can later run queries like fresult(X, Y, Z). to see all stored results, or fresult(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:50:16