我想弄清楚一个数字的阶乘。我的析法规则是在Prolog文件中,我将它连接到C ++文件。有人可以告诉我我的C ++与Prolog接口有什么问题吗?
my factorial.pl file:
factorial( 1, 1 ):-
!.
factorial( X, Fac ):-
X > 1,
Y is X - 1,
factorial( Y, New_Fac ),
Fac is X * New_Fac.
my factorial.cpp file:
headerfiles
term_t tf;
term_t tx;
term_t goal_term;
functor_t goal_functor;
int main( int argc, char** argv )
{
argv[0] = "libpl.dll";
PL_initialise(argc, argv);
PlCall( "consult('factorial.pl')" );
cout << "Enter your factorial number: ";
long nf;
cin >> nf;
tf = PL_new_term_ref();
PL_put_integer( tf, nf );
tx = PL_new_term_ref();
goal_term = PL_new_term_ref();
goal_functor = PL_new_functor( PL_new_atom("factorial"), 2 );
rval = PL_cons_functor( goal_term, goal_functor, tf, tx );
PL_halt( PL_toplevel() ? 0 : 1 );
}
我得到了Prolog提示符,这是最后一行的内容。但我没有得到因子计算的结果,例如:
?- factorial( 5, X ).
X = 120
true
我错过了什么?
谢谢,
答案 0 :(得分:1)
我并不熟悉SWI Prolog-C / C ++桥接器,但是在定义术语后,您似乎没有启动查询。您需要使用PL_call
或PL_open_query
,然后在将内容交给SWI-Prolog之前打印结果。
PL_cons_functor( goal_term, goal_functor, tf, tx );
int nfactorial;
if (PL_call(goal_term, NULL)) {
PL_get_integer(tx, &nfactorial);
std::cout << "X = " << nfactorial << " ." << std::endl;
} else {
PL_fail;
}
PL_halt( PL_toplevel() ? 0 : 1 );
我不知道您是否可以将goal_term
设置为顶级查询。如果您希望通过调用PL_toplevel
来运行查询,则可以将查询构建为字符串,并将其作为参数向量中的“-t”参数传递给PL_initialize
。
答案 1 :(得分:1)
# include files
term_t tf;
term_t tx;
term_t goal_term;
functor_t goal_functor;
int main( int argc, char** argv )
{
argv[0] = "libpl.dll";
PL_initialise( argc, argv );
PlCall( "consult( swi( 'plwin.rc' ) )" );
PlCall( "consult( 'factorial.pl' )" );
cout << " Enter your factorial number: ";
long nf;
cin >> nf;
tf = PL_new_term_ref();
PL_put_integer( tf, nf );
tx = PL_new_term_ref();
goal_term = PL_new_term_ref();
goal_functor = PL_new_functor( PL_new_atom("factorial"), 2 );
PL_cons_functor( goal_term, goal_functor, tf, tx );
int fact;
if( PL_call(goal_term, NULL) )
{
PL_get_integer( tx, &fact );
cout << fact << endl;
}
else
{
PL_fail;
}
PL_halt( PL_toplevel() ? 0 : 1 );
}