Factorial in Prolog and C++
I would like to work out a number's factorial. My factorial rule is in a Prolog file and I am connecting it to a C++ file. Can someone please tell me what is wrong with my interfacing C++ to 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 );
}
I get the Prolog prompt, which is what the last line does. But I don't get the result of the factorial calculation, such as:
?- factorial( 5, X ).
X = 120
true
What am I missing?
Thanks,
# 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 );
}
I'm not all that familiar with the SWI Prolog–C/C++ bridge, but it appears that you aren't initiating a query once you define the terms. You need to use PL_call
or PL_open_query
and then print the result before handing things over to 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 );
I don't know if you can set goal_term
as the top level query. If you want the query to be run by the call to PL_toplevel
, you could build the query as a string and pass it as a "-t" argument in the argument vector to PL_initialize
.
精彩评论