Next: Calling Prolog Asynchronously, Previous: Finding Multiple Solutions of a Call, Up: Calling Prolog from C [Contents][Index]
If you want to call Prolog multiple times in a loop for side effect, for example over the elements of a list, then some care is required in order not to cause a memory leak by creating more and more SP_term_refs. The recommended coding scheme is to use a backtracking loop (see Terminating a Backtracking Loop). For example, suppose that you want the C equivalent of the following code:
process_list(L) :- member(X, L), once(process(X)), fail. process_list(_). process(X) :- ...
That can be encoded as follows, where refL
is the SP_term_ref
that holds L
:
... SP_qid goal; SP_pred_ref member2 = SP_predicate("member", 2, "user"); SP_pred_ref process1 = SP_predicate("process", 1, "user"); SP_term_ref refX = SP_new_term_ref(); SP_put_variable(refX); goal = SP_open_query(member2, refX, refL); while (SP_next_solution(goal)==SP_SUCCESS) SP_query_cut_fail(process1, refX); SP_close_query(goal); ...
This programming style is particularly relevant in a stand-alone executable, where the top level iterates over some transactions to be processed.