评估prolog中的一个字符串项

问题描述 投票:0回答:1

我试图创建一个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).

在执行这个查询后,:

main(json([facts=['sick(martin)', '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。我试着用is2和the 召唤 谓词,但似乎不起作用。

使用

呼叫(术语)

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

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

使用

结果是Term

(结果是我添加的一个变量,用于存储结果),我遇到了这个错误。

Arithmetic: `does_albert_dance/0' is not a function

请问有什么办法可以解决在prolog中评估字符串表达式的问题吗?

prolog swi-prolog
1个回答
1
投票

正如 @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).

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

© www.soinside.com 2019 - 2024. All rights reserved.