2017-08-11 201 views
1

您好每个身体我有简单的prolog文件计算阶乘,我想知道如何咨询factorial.pl文件,并通过C++调用它的命名事实模块。如何将现有的prolog文件转换为C++及其模块?

这是我的示例代码,但它无法正常工作。

#include <iostream> 
using std::cout; 
using std::cin; 
using std::endl; 

#include <SWI-Prolog.h> 
#include <SWI-Stream.h> 
#include <SWI-cpp.h> 

int main(int argc, char **argv) 
{ 
    PL_initialise(argc, argv); 

    predicate_t p_consult = PL_predicate("consult", 1, "database"); 
    term_t t = PL_new_term_refs(3); 
    PL_put_string_chars(t, "D:\\factorial.pl"); 
    PL_put_integer(t + 1, 5); 
    PL_put_variable(t + 2); 
    qid_t query = PL_open_query(NULL, PL_Q_NORMAL, p_consult, t); 
    int result = PL_next_solution(query); 

    if (result) 
    { 
     int x; 
     PL_get_integer(t + 2, &x); 
     cout << "Found solution " << x << endl; 
    } 

    PL_close_query(query); 

    cin.ignore(); 
    return 0; 
} 

和factorial.pl

fact(N, F) :- N =< 1, F is 1. 
fact(N, F) :- N > 1, fact(N - 1, F1), F is F1 * N. 

回答

0

我发现我把答案在这里可能其他一些人有同样的问题的解决方案。

我的错误是在咨询,我猜,我用PlCall而不是谓语咨询PL源文件,由你应该把PL源文件的cpp文件相同的文件夹的方式英寸

#include <iostream> 
using std::cout; 
using std::cin; 
using std::endl; 

#include <SWI-Prolog.h> 
#include <SWI-Stream.h> 
#include <SWI-cpp.h> 

int main(int argc, char **argv) 
{ 
    int n; 
    cout << "Please enter a number: "; 
    cin >> n; 

    PL_initialise(argc, argv); 

    PlCall("consult('factorial.pl')"); 

    term_t a, b, ans; 
    functor_t func; 

    a = PL_new_term_ref(); 
    PL_put_integer(a, n); 
    b = PL_new_term_ref(); 
    ans = PL_new_term_ref(); 
    func = PL_new_functor(PL_new_atom("fact"), 2); 
    PL_cons_functor(ans, func, a, b); 

    int fact; 

    if (PL_call(ans, NULL)) 
    { 
     PL_get_integer(b, &fact); 
     cout << "Result is: " << fact << endl; 
    } 

    cin.ignore(2); 
    return 0; 
} 
相关问题