如何在Prolog中执行一行代码?

时间:2013-12-27 16:12:02

标签: prolog

我有一个代码,它将公式从中缀表示法转换为后缀表示法。还有代码确实评估方程式,我的问题是当我添加评估代码“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]).

1 个答案:

答案 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.