首页 > 解决方案 > 评估序言中的字符串术语

问题描述

我正在尝试创建一个 prolog 程序,它接收查询以作为字符串运行(通过 json),然后打印结果(成功或失败)。

:- use_module(library(http/json)).

happy(alice).
happy(albert).

with_albert(alice).

does_alice_dance :- happy(alice),with_albert(alice),
    format('When alice is happy and with albert, she dances ~n').

with_alice(albert).
does_albert_dance :- happy(albert),with_alice(albert),
    format('When albert is happy and with alice, he dances ~n').

fever(martin).
low_appetite(martin).
sick(X):-fever(X),low_appetite(X).

main(json(Request)) :- 
    nl,
    write(Request),
    nl,
    member(facts=Facts, Request),
    format('Facts : ~w ~n',[Facts]),

    atomic_list_concat(Facts, ', ', Atom),
    format('Atom : ~w ~n',[Atom]),

    atom_to_term(Atom,Term,Bindings),
    format('Term  : ~w ~n',Term),
    write(Bindings).

执行此查询后:

主要(json([事实=['病(马丁)','does_alice_dance','does_albert_dance']]))。

我有:

[facts=[sick(martin), does_alice_dance, does_albert_dance]]
Facts : [sick(martin),does_alice_dance,does_albert_dance] 
Atom : sick(martin), does_alice_dance, does_albert_dance 
Term  : sick(martin),does_alice_dance,does_albert_dance 
[]
true

我想做的是评估 Term。我尝试使用 is/2 和调用谓词使其工作,但它似乎不起作用。

使用

通话(期限)

(我在主体的尾部添加),我有这个错误:

Sandbox restriction!
Could not derive which predicate may be called from
      call(C)
      main(json([facts=['sick(martin)',does_alice_dance,does_albert_dance]]))

使用

结果是期限

(结果是我添加用于存储结果的变量),我有这个错误:

Arithmetic: `does_albert_dance/0' is not a function

请问有没有解决方案来评估序言中的字符串表达式?

标签: jsonprologswi-prologswi-prolog-for-sharing

解决方案


正如@David Tonhofer 在第一条评论中所说,问题是我正在在线编辑器上测试我的代码(这限制了一些 prolog 功能,如调用谓词的调用)。因此,将调用谓词添加到我的程序尾部之后:

main(json(Request)) :- 
    nl,
    write(Request),
    nl,
    member(facts=Facts, Request),
    format('Facts : ~w ~n',[Facts]),

    atomic_list_concat(Facts, ', ', Atom),
    format('Atom : ~w ~n',[Atom]),

    atom_to_term(Atom,Term,Bindings),
    format('Term  : ~w ~n',Term),
    write(Bindings),
    call(Term).

并在我的本地机器上测试它。它工作正常。


推荐阅读