带有pyswip的python中的序言代码不起作用

时间:2019-04-26 10:51:22

标签: python prolog swi-prolog

我的问题与this question有关。

我希望将以下prolog代码嵌入python程序中:

myEquation(A, B, C):- 
    var(A),number(B),number(C) -> A is B+C;
    var(B),number(A),number(C) -> B is A-C;
    var(C),number(A),number(B) -> C is A-B;
    A =:= B + C.

我安装了pyswip软件包并尝试了以下代码:

from pyswip import Prolog
prolog = Prolog()
prolog.assertz("myEquation(A, B, C):- var(A),number(B),number(C) -> A is B+C; var(B),number(A),number(C) -> B is A-C; var(C),number(A),number(B) -> C is A-B; A =:= B + C.")
prolog.assertz("myEquation(3,1,C).")

但这给了我错误:

ERROR: Syntax error: Operator priority clash
ERROR: assertz((myEquation(A, B, C):- var(A),number(B),number(C) -> A is B+C; var(B),number(A),number(C) -> B is A-C; var(C),number(A),number(B) -> C is A-B; A
ERROR: ** here **
ERROR:  =:= B + C.)). 
Traceback (most recent call last):
  File "prologpy.py", line 4, in <module>
    prolog.assertz("myEquation(A, B, C):- var(A),number(B),number(C) -> A is B+C; var(B),number(A),number(C) -> B is A-C; var(C),number(A),number(B) -> C is A-B; A =:= B + C.")
  File "/home/cardio/.local/lib/python3.5/site-packages/pyswip/prolog.py", line 140, in assertz
    next(cls.query(assertion.join(["assertz((", "))."]), catcherrors=catcherrors))
  File "/home/cardio/.local/lib/python3.5/site-packages/pyswip/prolog.py", line 127, in __call__
    "Returned: '", str(term), "'."]))
pyswip.prolog.PrologError: Caused by: 'assertz((myEquation(A, B, C):- var(A),number(B),number(C) -> A is B+C; var(B),number(A),number(C) -> B is A-C; var(C),number(A),number(B) -> C is A-B; A =:= B + C.)).'. Returned: 'error(syntax_error(operator_clash), string(b'assertz((myEquation(A, B, C):- var(A),number(B),number(C) -> A is B+C; var(B),number(A),number(C) -> B is A-C; var(C),number(A),number(B) -> C is A-B; A =:= B + C.)). ', 152))'.

如何解决此问题。我也可以像listed here一样使用其他一些与序言相关的python软件包。

1 个答案:

答案 0 :(得分:1)

谓词定义末尾的.太多。摆脱它。

例如,这是正确的:

?- assertz((foo :- bar)).

但这是不正确的:

?- assertz((foo :- bar.)).

如果您阅读示例provided with pyswip,则应注意,上面的本地Prolog代码转换为:

from pyswip import Prolog
prolog = Prolog()
prolog.assertz("(foo :- bar)")

不是,如您所写,

prolog.assertz("(foo :- bar.)")