将Prolog集成到C程序中

Integrate Prolog in C program

本文关键字:程序 Prolog 集成      更新时间:2023-10-16

我想用C++编写一个主程序,程序会动态生成事实来构建知识库,然后程序可以调用一些.pl文件中定义的规则并得到结果。例如主.c

int main()
{
   //generate facts like 
    // blue(car), red(bike), etc
    // do queries
    PL_call( "consult( 'pred.pl' )" );
    ...
    PL_call(goal_term, NULL);
}

pred.pl

whatisblue(X) :- blue(X).
whatisred(X) :- red(X).

我该怎么做?

我在 C 界面上阅读了 swi-prolog 手册,但只看到如何在 Prolog 中调用 C 模块或在 C 中调用 Prolog,我没有看到如何混合在 C 和 Prolog 中定义的谓词。可能吗?谢谢。

现在我

不可能有一个详细的答案,但总的来说,你的问题的答案是"是"。

只需在C++中使用C++界面。它比C容易得多。所以使用PlCall,PlTermv等...

问题是在 PlCall(s) 之前和之后正确绑定变量,以便您可以使用 Prolog 交换值。

例如,为了简化结构化值的构造,请查看这些宏注释、谓词0、谓词 1、...和结构1,结构2,...,或考虑

#define unary(X) PlTerm X; PlCompound X ## _t(#X, X);

允许输入代码

attrs2format_t::const_iterator p = attrs2format.find(k);
if (p == attrs2format.end()) {
    // attributes documented here:
    // http://www.swi-prolog.org/pldoc/doc_for?object=prolog_colour:syntax_colour/2
    unary(colour)
    unary(background)
    unary(bold)
    unary(underline)
    // use unification to match list' elements
    PlTail attrs(attr_list);
    PlTerm attr;
...

你可以在这里找到一些关于连接SWI-Prolog的一般说明