求助:实现输入±计算3±2的Prolog程序编译报错,如何解决?
Fixing Your Prolog Arithmetic Operator Program
Let's break down why your current code is failing and how to fix it properly.
Why Your Original Code Errors
Your code:
try(B):- read(A), B is A(3,2).
Runs into two main issues:
- Input Parsing Problem: When you type
+or-directly, Prolog'sread/1can't interpret it as a valid standalone term—these are infix operators, not atomic values. You'd have to input them as quoted atoms (like'+') just to getread/1to accept them, which is not user-friendly. - Arithmetic Expression Issue: Even if
Ais correctly read as'+',B is A(3,2)doesn't work as expected in most Prolog implementations. Theis/2predicate expects an arithmetic expression (like3+2), not a functor call syntax like+(3,2)(though they're logically equivalent,is/2doesn't always handle the latter smoothly).
Working Solutions
Solution 1: Explicit Conditional Checks (Simple & User-Friendly)
This approach directly handles each operator case and guides the user if they enter something invalid:
calculate_result(Result) :- write('Enter operator (+ or -): '), read_term(Op, [variable_names([])]), % Reads operator correctly even without quotes ( Op = (+) -> Result is 3 + 2 ; Op = (-) -> Result is 3 - 2 ; write('Oops! Please enter either + or -.'), nl, calculate_result(Result) % Retry on invalid input ).
- Using
read_term/2instead ofread/1lets users input+or-directly without quotes, which is much more intuitive. - The conditional branches (
->) explicitly map each operator to the correct arithmetic calculation.
Solution 2: Dynamic Expression Construction (More Flexible)
If you want to handle operators dynamically (scaling to more operators later), use the =../2 (univ) predicate to build the arithmetic expression:
calculate_result(Result) :- write('Enter operator (+ or -): '), read_term(Op, [variable_names([])]), ( member(Op, [+, -]) -> Expr =.. [Op, 3, 2], % Builds e.g., +(3,2) when Op is + Result is Expr ; write('Invalid operator! Try + or -.'), nl, calculate_result(Result) ).
=../2takes a functor and arguments and turns them into a term (or vice versa). Here, it constructs the arithmetic expression from the input operator, thenis/2evaluates it.
How to Test
Call the predicate in your Prolog interpreter:
?- calculate_result(R). Enter operator (+ or -): + R = 5. ?- calculate_result(R). Enter operator (+ or -): - R = 1.
内容的提问来源于stack exchange,提问作者Qwerto
相关产品推荐
相关产品推荐

