我有一个代码,它将公式从中缀表示法转换为后缀表示法。还有代码确实评估方程式,我的问题是当我添加评估代码“Y is Equation”时程序返回我的评估正确但方程的反转是错误的,这是我的代码:
fact(A + B, A, B, +).
fact(A - B, A, B, -).
fact(A * B, A, B, *).
fact(A / B, A, B, /).
topostfix(Equation, X,Y) :-
% y is Equation , -- I want to execute this line for once --
fact(Equation, A, B, Op),
!,
topostfix(A, AA),
topostfix(B, BB),
append(AA, BB, CC),
append(CC, [Op], X).
topostfix(X, [X]).
答案 0 :(得分:1)
错误在于您正在进行topostfix/2
谓词调用,而不是对topostfix/3
进行递归调用。尝试:
fact(A + B, A, B, +).
fact(A - B, A, B, -).
fact(A * B, A, B, *).
fact(A / B, A, B, /).
topostfix(Equation, X, Y) :-
Y is Equation,
fact(Equation, A, B, Op),
!,
topostfix(A, AA, _),
topostfix(B, BB, _),
append(AA, BB, CC),
append(CC, [Op], X).
topostfix(X, [X], X).
例如:
?- topostfix(2 + 3, X, Y).
X = [2, 3, +],
Y = 5.
?- topostfix(2 + 3 * 5, X, Y).
X = [2, 3, 5, *, +],
Y = 17.