6.5.3 Backtracking Loops

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),

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();
  goal = SP_open_query(member2, refX, refL);
  while (SP_next_solution(goal)==SP_SUCCESS)
    SP_query_cut_fail(process1, refX);

This programming style is particularly relevant in a stand-alone executable, where the top level iterates over some transactions to be processed.

Send feedback on this subject.