Re: non-deterministic external predicate in C++ ?

From: Joachim Schimpf <j.schimpf_at_icparc.ic.ac.uk>
Date: Tue 02 Oct 2001 01:18:08 PM GMT
Message-ID: <3BB9BE90.10798073@icparc.ic.ac.uk>
Manuel Weindorf wrote:
> 
> does anybody have a piece of example code in C++ for creating an external
> predicate which allows backtracking ??

The C/C++ interface does not have any special support for this.
You should instead write a small Eclipse wrapper to control the
backtracking.

For example, if your C function knew internally which
solution to return next, that could simply be:

p(X) :-
	c_pred(ThisX),	% compute a solution
	(
	    X = ThisX	% succeed with this solution
	;
	    p(X)	% on backtracking, call it again
	).


Normally, however, you will need to remember somehow how
many solutions have already been returned. This is best done
by passing a "state" argument from one invocation of the
C external to the next, i.e.

p(X) :-
	p_aux(X, <initial state>).

    p_aux(X, OldState) :-
	c_pred(ThisX, OldState, NewState),
	(
	    X = ThisX
	;
	    p_aux(X, NewState)
	).

This state could be a numeric counter, the rest of a list
or something else which is convenient.  The C external takes
the old state as input, decides on the next solution, and
returns that solution and the new state as outputs. When
there are no more solutions, the C external should fail.

As a final optimisation, sometimes you can test whether
a solution is the last one, in which case you don't need
to make another choice point.

Cheers,
Joachim
-- 
 Joachim Schimpf              /             phone: +44 20 7594 8187
 IC-Parc, Imperial College   /            mailto:J.Schimpf@ic.ac.uk
 London SW7 2AZ, UK         /    http://www.icparc.ic.ac.uk/eclipse
Received on Tue Oct 02 14:19:24 2001

This archive was generated by hypermail 2.1.8 : Wed 16 Nov 2005 06:07:10 PM GMT GMT