Sophie

Sophie

distrib > Mandriva > 9.1 > ppc > by-pkgid > d1f06a5336fd6bf4a381b72b8d2b5ce1 > files > 201

gprolog-1.2.16-3mdk.ppc.rpm

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
            "http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML>
<HEAD>

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="hevea 1.06-7 of 2001-11-14">
<TITLE>
 Calling C from Prolog
</TITLE>
</HEAD>
<BODY TEXT=black BGCOLOR=white>
<A HREF="manual065.html"><IMG SRC ="contents_motif.gif" ALT="Contents"></A>
<A HREF="manual067.html"><IMG SRC ="next_motif.gif" ALT="Next"></A>
<HR>
<TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%">
<TR><TD BGCOLOR="#66dbff"><DIV ALIGN=center><TABLE>
<TR><TD><FONT SIZE=4><B><A NAME="htoc341">9.1</A></B></FONT></TD>
<TD WIDTH="100%" ALIGN=center><FONT SIZE=4><B>Calling C from Prolog</B></FONT></TD>
</TR></TABLE></DIV></TD>
</TR></TABLE><UL>
<LI><A HREF="manual066.html#toc277"> Introduction</A>
<LI><A HREF="manual066.html#toc278"> <TT>foreign/2</TT> directive</A>
<LI><A HREF="manual066.html#toc279"> The C function</A>
<LI><A HREF="manual066.html#toc280"> Input arguments</A>
<LI><A HREF="manual066.html#toc281"> Output arguments</A>
<LI><A HREF="manual066.html#toc282"> Input/output arguments</A>
<LI><A HREF="manual066.html#toc283"> Writing non-deterministic C code</A>
<LI><A HREF="manual066.html#toc284"> Example: input and output arguments</A>
<LI><A HREF="manual066.html#toc285"> Example: non-deterministic code</A>
<LI><A HREF="manual066.html#toc286"> Example: input/output arguments</A>
</UL>

<A NAME="Calling-C-from-Prolog"></A><BR>
<A NAME="toc277"></A><TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%">
<TR><TD BGCOLOR="#98e7ff"><DIV ALIGN=center><TABLE>
<TR><TD><B><A NAME="htoc342">9.1.1</A></B></TD>
<TD WIDTH="100%" ALIGN=center><B>Introduction</B></TD>
</TR></TABLE></DIV></TD>
</TR></TABLE>
This interface allows a Prolog predicate to call a C function. Here are some
features of this facility:
<UL><LI>implicit Prolog &lt;-&gt; C data conversions for simple types.<BR>
<BR>
<LI>functions to handle complex types.<BR>
<BR>
<LI>error detection depending on the type of the argument.<BR>
<BR>
<LI>different kinds of arguments: input, output or input/output.<BR>
<BR>
<LI>possibility to write non-deterministic code.</UL>
This interface can then be used to write both simple and complex C routines.
A simple routine uses either input or output arguments which type is simple.
In that case the user does not need any knowledge of Prolog data structures
since all Prolog &lt;-&gt; C data conversions are implicitly
achieved. To manipulate complex terms (lists, structures) a set of
functions is provided. Finally it is also possible to write
non-deterministic C code.<BR>
<BR>
<A NAME="toc278"></A><TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%">
<TR><TD BGCOLOR="#98e7ff"><DIV ALIGN=center><TABLE>
<TR><TD><B><A NAME="htoc343">9.1.2</A></B></TD>
<TD WIDTH="100%" ALIGN=center><B><TT>foreign/2</TT> directive</B></TD>
</TR></TABLE></DIV></TD>
</TR></TABLE>
<A NAME="foreign/2-directive"></A>
 
 <BR>
<TT>foreign/2</TT> directive (section&nbsp;<A HREF="manual021.html#foreign/2">6.1.14</A>) declares a C function interface. 
The general form is <TT>foreign(Template, Options)</TT> which defines an
interface predicate whose prototype is <TT>Template</TT> according to the
options given by <TT>Options</TT>. <TT>Template</TT> is a callable term
specifying the type/mode of each argument of the associated Prolog predicate.<BR>
<BR>
<B>Foreign options</B>: <TT>Options</TT> is a list of foreign options. If
this list contains contradictory options, the rightmost option is the one
which applies. Possible options are:
<UL><LI><TT>fct_name(F)</TT>: <TT>F</TT> is an atom representing
the name of the C function to call. By default the name of the C function is
the same as the principal functor of <TT>Template</TT>. In any case, the atom
associated to the name of the function must conforms to the syntax of C
identifiers.<BR>
<BR>
<LI><TT>return(boolean</TT>/<TT>none</TT>/<TT>jump)</TT>:
specifies the value returned by the C function:
<UL><LI><TT>boolean</TT>: the type of the function is <TT>Bool</TT> (returns
<TT>TRUE</TT> on success, <TT>FALSE</TT> otherwise).<BR>
<BR>
<LI><TT>none</TT>: the type of the function is <TT>void</TT> (no returned
value).<BR>
<BR>
<LI><TT>jump</TT>: the type of the function is <TT>void(*)()</TT> (returns
the address of a Prolog code to execute).</UL><BR>
The default value is <TT>boolean</TT>.<BR>
<BR>
<LI><TT>bip_name(Name, Arity)</TT>: initializes the error
context with <TT>Name</TT> and <TT>Arity</TT>. If an error occurs this
information is used to indicate from which predicate the error occurred
(section&nbsp;<A HREF="manual019.html#General-format-and-error-context">5.3.1</A>). It is also possible to prevent the
initialization of the error context using <TT>bip_name(none)</TT>. By
default <TT>Name</TT> and <TT>Arity</TT> are set to the functor and arity of
<TT>Template</TT>.<BR>
<BR>
<LI><TT>choice_size(N)</TT>: this option specifies that the
function implements a non-deterministic code. <TT>N</TT> is an integer
specifying the size needed by the non-deterministic C function. This facility
is explained later (section&nbsp;<A HREF="#Writing-non-deterministic-C-code">9.1.7</A>). By default a
foreign function is deterministic.</UL>
<TT>foreign(Template)</TT> is equivalent to
<TT>foreign(Template, [])</TT>.<BR>
<BR>
<B>Foreign modes and types</B>: each argument of <TT>Template</TT>
specifies the foreign mode and type of the corresponding argument. This
information is used to check the type of effective arguments at run-time and
to perform Prolog &lt;-&gt; C data conversions. Each argument of
<TT>Template</TT> is formed with a mode symbol followed by a type name.
Possible foreign modes are:
<UL><LI><TT>+</TT>: input argument.<BR>
<BR>
<LI><TT>-</TT>: output argument.<BR>
<BR>
<LI><TT>?</TT>: input/output argument.</UL>
Possible foreign types are:<BR>
<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=1>
<TR><TD ALIGN=left NOWRAP>Foreign type</TD>
<TD ALIGN=left NOWRAP>Prolog type</TD>
<TD ALIGN=left NOWRAP>C type</TD>
<TD ALIGN=left NOWRAP>Description of the C type</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>integer</TT></TD>
<TD ALIGN=left NOWRAP>integer</TD>
<TD ALIGN=left NOWRAP><TT>long</TT></TD>
<TD ALIGN=left NOWRAP>value of the integer</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>positive</TT></TD>
<TD ALIGN=left NOWRAP>positive integer</TD>
<TD ALIGN=left NOWRAP><TT>long</TT></TD>
<TD ALIGN=left NOWRAP>value of the integer</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>float</TT></TD>
<TD ALIGN=left NOWRAP>floating point number</TD>
<TD ALIGN=left NOWRAP><TT>double</TT></TD>
<TD ALIGN=left NOWRAP>value of the
floating point number</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>number</TT></TD>
<TD ALIGN=left NOWRAP>number</TD>
<TD ALIGN=left NOWRAP><TT>double</TT></TD>
<TD ALIGN=left NOWRAP>value of the number</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>atom</TT></TD>
<TD ALIGN=left NOWRAP>atom</TD>
<TD ALIGN=left NOWRAP><TT>int</TT></TD>
<TD ALIGN=left NOWRAP>internal key of the atom</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>boolean</TT></TD>
<TD ALIGN=left NOWRAP>boolean</TD>
<TD ALIGN=left NOWRAP><TT>int</TT></TD>
<TD ALIGN=left NOWRAP>value of the boolean
(0=<TT>false</TT>, 1=<TT>true</TT>)</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>char</TT></TD>
<TD ALIGN=left NOWRAP>character</TD>
<TD ALIGN=left NOWRAP><TT>int</TT></TD>
<TD ALIGN=left NOWRAP>value of (the code of) the
character</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>code</TT></TD>
<TD ALIGN=left NOWRAP>character code</TD>
<TD ALIGN=left NOWRAP><TT>int</TT></TD>
<TD ALIGN=left NOWRAP>value of the character-code</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>byte</TT></TD>
<TD ALIGN=left NOWRAP>byte</TD>
<TD ALIGN=left NOWRAP><TT>int</TT></TD>
<TD ALIGN=left NOWRAP>value of the byte</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>in_char</TT></TD>
<TD ALIGN=left NOWRAP>in-character</TD>
<TD ALIGN=left NOWRAP><TT>int</TT></TD>
<TD ALIGN=left NOWRAP>value of the character or
<TT>-1</TT> for end-of-file</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>in_code</TT></TD>
<TD ALIGN=left NOWRAP>in-character code</TD>
<TD ALIGN=left NOWRAP><TT>int</TT></TD>
<TD ALIGN=left NOWRAP>value of the
character-code or <TT>-1</TT> for end-of-file</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>in_byte</TT></TD>
<TD ALIGN=left NOWRAP>in-byte</TD>
<TD ALIGN=left NOWRAP><TT>int</TT></TD>
<TD ALIGN=left NOWRAP>value of the byte or
<TT>-1</TT> for the end-of-file</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>string</TT></TD>
<TD ALIGN=left NOWRAP>atom</TD>
<TD ALIGN=left NOWRAP><TT>char *</TT></TD>
<TD ALIGN=left NOWRAP>C string containing the name of
the atom</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>chars</TT></TD>
<TD ALIGN=left NOWRAP>character list</TD>
<TD ALIGN=left NOWRAP><TT>char *</TT></TD>
<TD ALIGN=left NOWRAP>C string containing the
characters of the list</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>codes</TT></TD>
<TD ALIGN=left NOWRAP>character-code list</TD>
<TD ALIGN=left NOWRAP><TT>char *</TT></TD>
<TD ALIGN=left NOWRAP>C string containing
the characters of the list</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>term</TT></TD>
<TD ALIGN=left NOWRAP>Prolog term</TD>
<TD ALIGN=left NOWRAP><TT>PlTerm</TT></TD>
<TD ALIGN=left NOWRAP>generic Prolog term</TD>
</TR></TABLE><BR>
<B>Simple foreign type</B>: a simple type is any foreign type listed in
the above tabled except <TT>term</TT>. A simple foreign type is an atomic
term (character and character-code lists are in fact lists of constants).
Each simple foreign type is converted to/from a C type to simplify the
writing of the C function.<BR>
<BR>
<B>Complex foreign type</B>: type foreign type <TT>term</TT> refers to any
Prolog term (e.g. lists, structures...). When such an type is
specified the argument is passed to the C function as a <TT>PlTerm</TT>
(GNU Prolog C type equivalent to a <TT>long</TT>). Several functions are
provided to manipulate <TT>PlTerm</TT> variables (section&nbsp;<A HREF="manual067.html#Manipulating-Prolog-terms">9.2</A>). Since the original term is passed to the function it is
possible to read its value or to unify it. So the meaning of the mode symbol
is less significant. For this reason it is possible to omit the mode symbol.
In that case <TT>term</TT> is equivalent to <TT>+term</TT>.<BR>
<BR>
<A NAME="toc279"></A><TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%">
<TR><TD BGCOLOR="#98e7ff"><DIV ALIGN=center><TABLE>
<TR><TD><B><A NAME="htoc344">9.1.3</A></B></TD>
<TD WIDTH="100%" ALIGN=center><B>The C function</B></TD>
</TR></TABLE></DIV></TD>
</TR></TABLE>
The C code is written in a C file which must first include the GNU Prolog
header file called <TT>gprolog.h</TT>. This file contains all GNU Prolog C
definitions (constants, types, prototypes,...). <BR>
<BR>
The type returned by a C function depends on the value of the
<TT>return</TT> foreign option (section&nbsp;<A HREF="#foreign/2-directive">9.1.2</A>). If it is
<TT>boolean</TT> then the C function is of type <TT>Bool</TT> and shall
return <TT>TRUE</TT> in case of success and <TT>FALSE</TT> otherwise. If the
<TT>return</TT> option is <TT>none</TT> the C function is of type
<TT>void</TT>. Finally if it is <TT>jump</TT>, the function shall return the
address of a Prolog predicate and, at the exit of the function, the control
is given to that predicate.<BR>
<BR>
The type of the arguments of the C function depends on the mode and type
declaration specified in <TT>Template</TT> for the corresponding argument as
explained in the following sections.<BR>
<BR>
<A NAME="toc280"></A><TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%">
<TR><TD BGCOLOR="#98e7ff"><DIV ALIGN=center><TABLE>
<TR><TD><B><A NAME="htoc345">9.1.4</A></B></TD>
<TD WIDTH="100%" ALIGN=center><B>Input arguments</B></TD>
</TR></TABLE></DIV></TD>
</TR></TABLE>
<A NAME="Input-arguments"></A>
An input argument is tested at run-time to check if its type conforms to the
foreign type and then it is passed to the C function. The type of the
associated C argument is given by the above table (section&nbsp;<A HREF="#foreign/2-directive">9.1.2</A>). For instance, the effective argument <TT>Arg</TT> associated to
<TT>+positive</TT> foreign declaration is submitted to the following
process:
<UL><LI>if <TT>Arg</TT> is a variable an <TT>instantiation_error</TT> is
raised.<BR>
<BR>
<LI>if <TT>Arg</TT> is neither a variable nor an integer a
<TT>type_error(integer, Arg)</TT> is raised.<BR>
<BR>
<LI>if <TT>Arg</TT> is an integer &lt; 0 a
<TT>domain_error(not_less_than_zero, Arg)</TT> is raised.<BR>
<BR>
<LI>otherwise the value of <TT>Arg</TT> is passed to the C is passed to
the C function as an integer (<TT>long</TT>).</UL>
When <TT>+string</TT> is specified the string passed to the function is the
internal string of the corresponding atom and should not be modified.<BR>
<BR>
When <TT>+term</TT> is specified the term passed to the function is the
original Prolog term. It can be read and/or unified. It is also the case
when <TT>term</TT> is specified without any mode symbol.<BR>
<BR>
<A NAME="toc281"></A><TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%">
<TR><TD BGCOLOR="#98e7ff"><DIV ALIGN=center><TABLE>
<TR><TD><B><A NAME="htoc346">9.1.5</A></B></TD>
<TD WIDTH="100%" ALIGN=center><B>Output arguments</B></TD>
</TR></TABLE></DIV></TD>
</TR></TABLE>
<A NAME="Output-arguments"></A>
An output argument is tested at run-time to check if its type conforms to
the foreign type and it is unified with the value set by the C function. The
type of the associated C argument is a pointer to the type given by the
above table (section&nbsp;<A HREF="#foreign/2-directive">9.1.2</A>). For instance, the effective
argument <TT>Arg</TT> associated to <TT>-positive</TT> foreign declaration
is handled as follows:
<UL><LI>if <TT>Arg</TT> is neither a variable nor an integer a
<TT>type_error(integer, Arg)</TT> is raised.<BR>
<BR>
<LI>if <TT>Arg</TT> is an integer &lt; 0 a
<TT>domain_error(not_less_than_zero, Arg)</TT> is raised.<BR>
<BR>
<LI>otherwise a pointer to an integer (<TT>long</TT> <TT>*</TT>) is passed
to the C function. If the function returns <TT>TRUE</TT> the integer stored
at this location is unified with <TT>Arg</TT>.</UL>
When <TT>-term</TT> is specified, the function must construct a term into
the its corresponding argument (which is of type <TT>PlTerm *</TT>). At the
exit of the function this term will be unified with the actual predicate
argument.<BR>
<BR>
<A NAME="toc282"></A><TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%">
<TR><TD BGCOLOR="#98e7ff"><DIV ALIGN=center><TABLE>
<TR><TD><B><A NAME="htoc347">9.1.6</A></B></TD>
<TD WIDTH="100%" ALIGN=center><B>Input/output arguments</B></TD>
</TR></TABLE></DIV></TD>
</TR></TABLE>
<A NAME="Input/output-arguments"></A>
Basically an input/output argument is treated as in input argument if it is
not a variable, as an output argument otherwise. The type of the associated
C argument is a pointer to a <TT>FIOArg</TT> (GNU Prolog C type) defined as
follows:
<DL COMPACT=compact><DT><DD>
<PRE>
typedef struct
    {
     Bool is_var;
     Bool unify;
     union
        {
         long   l;
         char  *s;
         double d;
        }value;
    }FIOArg;
</PRE></DL>
The field <TT>is_var</TT> is set to <TT>TRUE</TT> if the argument is a
variable and <TT>FALSE</TT> otherwise. This value can be tested by the C
function to determine which treatment to perform. The field <TT>unify</TT>
controls whether the effective argument must be unified at the exit of the C
function. Initially <TT>unify</TT> is set to the same value as
<TT>is_var</TT> (i.e. a variable argument will be unified while a
non-variable argument will not) but it can be modified by the C function.
The field <TT>value</TT> stores the value of the argument. It is declared as
a C <TT>union</TT> since there are several kinds of value types. The field
<TT>s</TT> is used for C strings, <TT>d</TT> for C doubles and <TT>l</TT>
otherwise (<TT>int</TT>, <TT>long</TT>, <TT>PlTerm</TT>). if <TT>is_var</TT>
is <TT>FALSE</TT> then <TT>value</TT> contains the input value of the
argument with the same conventions as for input arguments
(section&nbsp;<A HREF="#Input-arguments">9.1.4</A>). At the exit of the function, if unify is
<TT>TRUE</TT> <TT>value</TT> must contain the value to unify with the same
conventions as for output arguments
(section&nbsp;<A HREF="#Output-arguments">9.1.5</A>).<BR>
<BR>
For instance, the effective argument <TT>Arg</TT> associated to
<TT>?positive</TT> foreign declaration is handled as follows:
<UL><LI>if <TT>Arg</TT> is a variable <TT>is_var</TT> and <TT>unify</TT> are
set to <TT>TRUE</TT> else to <TT>FALSE</TT> and its value is copied in
<TT>value.l</TT>.<BR>
<BR>
<LI>if <TT>Arg</TT> is neither a variable nor an integer a
<TT>type_error(integer, Arg)</TT> is raised.<BR>
<BR>
<LI>if <TT>Arg</TT> is an integer &lt; 0 a
<TT>domain_error(not_less_than_zero, Arg)</TT> is raised.<BR>
<BR>
<LI>otherwise a pointer to the <TT>FIOArg</TT> (<TT>FIOArg</TT>
<TT>*</TT>) is passed to the C function. If the function returns
<TT>TRUE</TT> and if <TT>unify</TT> is TRUE the value stored in
<TT>value.l</TT> is unified with <TT>Arg</TT>.</UL>
<A NAME="toc283"></A><TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%">
<TR><TD BGCOLOR="#98e7ff"><DIV ALIGN=center><TABLE>
<TR><TD><B><A NAME="htoc348">9.1.7</A></B></TD>
<TD WIDTH="100%" ALIGN=center><B>Writing non-deterministic C code</B></TD>
</TR></TABLE></DIV></TD>
</TR></TABLE>
<A NAME="Writing-non-deterministic-C-code"></A>
The interface allows the user to write non-deterministic C code. When a C
function is non-deterministic, a choice-point is created for this function.
When a failure occurs, if all more recent non-deterministic code are
finished, the function is re-invoked. It is then important to inform Prolog
when there is no more solution (i.e. no more choice) for a non-deterministic
code. So, when no more choices remains the function must remove the
choice-point. The interface increments a counter each time the function is
re-invoked. At the first call this counter is equal to 0. This information
allows the function to detect its first call. When writing non-deterministic
code, it is often useful to record data between consecutive re-invocations
of the function. The interface maintains a buffer to record such an
information. The size of this buffer is given by
<TT>choice_size(N)</TT> when using <TT>foreign/2</TT>
(section&nbsp;<A HREF="#foreign/2-directive">9.1.2</A>). This size is the number of (consecutive)
<TT>long</TT><EM>s</EM> needed by the C function. Inside the function it is
possible to call the following functions/macros:
<DL COMPACT=compact><DT><DD>
<PRE>
void Get_Choice_Counter(void)
TYPE Get_Choice_Buffer (TYPE)
void No_More_Choice    (void)
</PRE></DL>
The function <TT>Get_Choice_Counter()</TT> returns the value of the
invocation counter (0 at the first call).<BR>
<BR>
The macro <TT>Get_Choice_Buffer(<I>TYPE</I>)</TT> returns a
pointer to the buffer (casted to <I><TT>TYPE</TT></I>).<BR>
<BR>
The function <TT>No_More_Choice()</TT> deletes the choice point
associated to the function.<BR>
<BR>
<A NAME="toc284"></A><TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%">
<TR><TD BGCOLOR="#98e7ff"><DIV ALIGN=center><TABLE>
<TR><TD><B><A NAME="htoc349">9.1.8</A></B></TD>
<TD WIDTH="100%" ALIGN=center><B>Example: input and output arguments</B></TD>
</TR></TABLE></DIV></TD>
</TR></TABLE>
All examples presented here can be found in the <TT>ExamplesC</TT>
sub-directory of the distribution, in the files <TT>examp.pl</TT> (Prolog
part) and <TT>examp_c.c</TT> (C part).<BR>
<BR>
Let us define a predicate <TT>first_occurrence(A, C, P)</TT> which unifies
<TT>P</TT> with the position (from 0) of the first occurrence of the
character <TT>C</TT> in the atom <TT>A</TT>. The predicate must fail if
<TT>C</TT> does not appear in <TT>A</TT>.<BR>
<BR>
In the prolog file <TT>examp.pl</TT>:
<DL COMPACT=compact><DT><DD><TT>:- foreign(first_occurrence(+string, +char, -positive)).</TT></DL>
In the C file <TT>examp_c.c</TT>:
<DL COMPACT=compact><DT><DD>
<PRE>
#include &lt;string.h&gt;
#include "gprolog.h"

Bool
first_occurrence(char *str, long c, long *pos)
{
  char *p;

  p = strchr(str, c);
  if (p == NULL)                /* C does not appear in A */
    return FALSE;               /* fail */

  *pos = p - str;               /* set the output argument */
  return TRUE;                  /* succeed */
}
</PRE></DL>
The compilation produces an executable called <TT>examp</TT>:
<DL COMPACT=compact><DT><DD><TT>% gplc examp.pl examp_c.c</TT></DL>
Examples of use:
<DL COMPACT=compact><DT><DD>
<PRE>
| ?- first_occurrence(prolog, p, X).

X = 0

| ?- first_occurrence(prolog, k, X).

no

| ?- first_occurrence(prolog, A, X).
{exception: error(instantiation_error,first_occurrence/3)}

| ?- first_occurrence(prolog, 1 ,X).
{exception: error(type_error(character,1),first_occurrence/3)}
</PRE></DL>
<A NAME="toc285"></A><TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%">
<TR><TD BGCOLOR="#98e7ff"><DIV ALIGN=center><TABLE>
<TR><TD><B><A NAME="htoc350">9.1.9</A></B></TD>
<TD WIDTH="100%" ALIGN=center><B>Example: non-deterministic code</B></TD>
</TR></TABLE></DIV></TD>
</TR></TABLE>
We here define a predicate <TT>occurrence(A, C, P)</TT> which unifies
<TT>P</TT> with the position (from 0) of one occurrence of the character
<TT>C</TT> in the atom <TT>A</TT>. The predicate will fail if <TT>C</TT>
does not appear in <TT>A</TT>. The predicate is re-executable on
backtracking. The information that must be recorded between two invocations
of the function is the next starting position in <TT>A</TT> to search for
<TT>C</TT>.<BR>
<BR>
In the prolog file <TT>examp.pl</TT>:
<DL COMPACT=compact><DT><DD><TT>:- foreign(occurrence(+string, +char, -positive), 
[choice_size(1)]).</TT></DL>
In the C file <TT>examp_c.c</TT>:
<DL COMPACT=compact><DT><DD>
<PRE>
#include &lt;string.h&gt;
#include "gprolog.h"

Bool
occurrence(char *str, long c, long *pos)
{
  char **info_pos;
  char *p;

  info_pos = Get_Choice_Buffer(char **); /* recover the buffer */

  if (Get_Choice_Counter() == 0)        /* first invocation ? */
    *info_pos = str;

  p = strchr(*info_pos, c);
  if (p == NULL)                /* C does not appear */
    {
      No_More_Choice();         /* remove choice-point */
      return FALSE;             /* fail */
    }

  *pos = p - str;               /* set the output argument */
  *info_pos = p + 1;            /* update next starting pos */
  return TRUE;                  /* succeed */
}
</PRE></DL>
The compilation produces an executable called <TT>examp</TT>:
<DL COMPACT=compact><DT><DD><TT>% gplc examp.pl examp_c.c</TT></DL>
Examples of use:
<DL COMPACT=compact><DT><DD><TABLE CELLSPACING=2 CELLPADDING=0>
<TR><TD ALIGN=left NOWRAP COLSPAN=3><TT>| ?- occurrence(prolog, o, X).</TT></TD>
</TR>
<TR><TD ALIGN=left NOWRAP COLSPAN=3>&nbsp;</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>X = 2 ?</TT></TD>
<TD VALIGN=top ALIGN=center NOWRAP>&nbsp;&nbsp;</TD>
<TD ALIGN=left NOWRAP>(here the user presses <TT>;</TT> to compute another solution)</TD>
</TR>
<TR><TD ALIGN=left NOWRAP COLSPAN=3>&nbsp;</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>X = 4 ?</TT></TD>
<TD VALIGN=top ALIGN=center NOWRAP>&nbsp;&nbsp;</TD>
<TD ALIGN=left NOWRAP>(here the user presses <TT>;</TT> to compute another solution)</TD>
</TR>
<TR><TD ALIGN=left NOWRAP COLSPAN=3>&nbsp;</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>no</TT></TD>
<TD VALIGN=top ALIGN=center NOWRAP>&nbsp;&nbsp;</TD>
<TD ALIGN=left NOWRAP>(no more solution)</TD>
</TR>
<TR><TD ALIGN=left NOWRAP COLSPAN=3>&nbsp;</TD>
</TR>
<TR><TD ALIGN=left NOWRAP COLSPAN=3><TT>| ?- occurrence(prolog, k, X).</TT></TD>
</TR>
<TR><TD ALIGN=left NOWRAP COLSPAN=3>&nbsp;</TD>
</TR>
<TR><TD ALIGN=left NOWRAP COLSPAN=3><TT>no</TT></TD>
</TR></TABLE></DL>
In the first example when the second (the last) occurrence is found
(<TT>X=4</TT>) the choice-point remains and the failure is detected only when
another solution is requested (by pressing <TT>;</TT>). It is possible to
improve this behavior by deleting the choice-point when there is no more
occurrence. To do this it is necessary to do one search ahead. The
information stored is the position of the next occurrence. Let us define such
a behavior for the predicate <TT>occurrence2/3</TT>.<BR>
<BR>
In the prolog file <TT>examp.pl</TT>:
<DL COMPACT=compact><DT><DD><TT>:- foreign(occurrence2(+string, +char, -positive), 
[choice_size(1)]).</TT></DL>
In the C file <TT>examp_c.c</TT>:
<DL COMPACT=compact><DT><DD>
<PRE>
#include &lt;string.h&gt;
#include "gprolog.h"

Bool
occurrence2(char *str, long c, long *pos)
{
  char **info_pos;
  char *p;

  info_pos = Get_Choice_Buffer(char **); /* recover the buffer */

  if (Get_Choice_Counter() == 0) /* first invocation ? */
    {
      p = strchr(str, c);
      if (p == NULL)            /* C does not appear at all */
        {
          No_More_Choice();     /* remove choice-point */
          return FALSE;         /* fail */
        }

      *info_pos = p;
    }
                                /* info_pos = an occurrence */
  *pos = *info_pos - str;       /* set the output argument */

  p = strchr(*info_pos + 1, c);
  if (p == NULL)                /* no more occurrence */
    No_More_Choice();           /* remove choice-point */
  else
    *info_pos = p;              /* else update next solution */

  return TRUE;                  /* succeed */
}
</PRE></DL>
Examples of use:
<DL COMPACT=compact><DT><DD><TABLE CELLSPACING=2 CELLPADDING=0>
<TR><TD ALIGN=left NOWRAP COLSPAN=3><TT>| ?- occurrence2(prolog, l, X).</TT></TD>
</TR>
<TR><TD ALIGN=left NOWRAP COLSPAN=3>&nbsp;</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>X = 3</TT></TD>
<TD VALIGN=top ALIGN=center NOWRAP>&nbsp;&nbsp;</TD>
<TD ALIGN=left NOWRAP>(here the user is not prompted since there is no more alternative)</TD>
</TR>
<TR><TD ALIGN=left NOWRAP COLSPAN=3>&nbsp;</TD>
</TR>
<TR><TD ALIGN=left NOWRAP COLSPAN=3><TT>| ?- occurrence2(prolog, o, X).</TT></TD>
</TR>
<TR><TD ALIGN=left NOWRAP COLSPAN=3>&nbsp;</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>X = 2 ?</TT></TD>
<TD VALIGN=top ALIGN=center NOWRAP>&nbsp;&nbsp;</TD>
<TD ALIGN=left NOWRAP>(here the user presses <TT>;</TT> to compute another solution)</TD>
</TR>
<TR><TD ALIGN=left NOWRAP COLSPAN=3>&nbsp;</TD>
</TR>
<TR><TD ALIGN=left NOWRAP><TT>X = 4</TT></TD>
<TD VALIGN=top ALIGN=center NOWRAP>&nbsp;&nbsp;</TD>
<TD ALIGN=left NOWRAP>(here the user is not prompted since there is no more alternative)</TD>
</TR></TABLE></DL>
<A NAME="toc286"></A><TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%">
<TR><TD BGCOLOR="#98e7ff"><DIV ALIGN=center><TABLE>
<TR><TD><B><A NAME="htoc351">9.1.10</A></B></TD>
<TD WIDTH="100%" ALIGN=center><B>Example: input/output arguments</B></TD>
</TR></TABLE></DIV></TD>
</TR></TABLE>
We here define a predicate <TT>char_ascii(Char, Code</TT>) which converts
in both directions the character <TT>Char</TT> and its character-code
<TT>Code</TT>. This predicate is then similar to <TT>char_code/2</TT>
(section&nbsp;<A HREF="manual042.html#char-code/2">7.19.4</A>).<BR>
<BR>
In the prolog file <TT>examp.pl</TT>:
<DL COMPACT=compact><DT><DD><TT>:- foreign(char_ascii(?char, ?code), [fct_name('Char_Ascii')]).</TT></DL>
In the C file <TT>examp_c.c</TT>:
<DL COMPACT=compact><DT><DD>
<PRE>
#include "gprolog.h"

Bool
char_ascii(FIOArg *c, FIOArg *ascii)
{
  if (!c-&gt;is_var)               /* Char is not a variable */
    {
      ascii-&gt;unify = TRUE;      /* enforce unif. of Code */
      ascii-&gt;value.l = c-&gt;value.l; /* set Code */
      return TRUE;              /* succeed */
    }

  if (ascii-&gt;is_var)            /* Code is also a variable */
    Pl_Err_Instantiation();     /* emit instantiation_error */

  c-&gt;value.l = ascii-&gt;value.l;  /* set Char */
  return TRUE;                  /* succeed */
}
</PRE></DL>
If <TT>Char</TT> is instantiated it is necessary to enforce the unification
of <TT>Code</TT> since it could be instantiated. Recall that by default if
an input/output argument is instantiated it will not be unified at the exit
of the function (section&nbsp;<A HREF="#Input/output-arguments">9.1.6</A>). If both <TT>Char</TT> and
<TT>Code</TT> are variables the function raises an
<TT>instantiation_error</TT>. The way to raise Prolog errors is described
later (section&nbsp;<A HREF="manual068.html#Raising-Prolog-errors">9.3</A>).<BR>
<BR>
The compilation produces an executable called <TT>examp</TT>:
<DL COMPACT=compact><DT><DD><TT>% gplc examp.pl examp_c.c</TT></DL>
Examples of use:
<DL COMPACT=compact><DT><DD>
<PRE>
| ?- char_ascii(a, X).

X = 97

| ?- char_ascii(X, 65).

X = 'A'

| ?- char_ascii(a, 12).

no

| ?- char_ascii(X, X).
{exception: error(instantiation_error,char_ascii/2)}

| ?- char_ascii(1, 12).
{exception: error(type_error(character,1),char_ascii/2)}
</PRE></DL>

<HR SIZE=2>
Copyright (C) 1999-2002 Daniel Diaz
<BR>
<BR>
Verbatim copying and distribution of this entire article is permitted in any
medium, provided this notice is preserved. <BR>
<BR>
<A HREF="index.html#copyright">More about the copyright</A>
<HR>
<A HREF="manual065.html"><IMG SRC ="contents_motif.gif" ALT="Contents"></A>
<A HREF="manual067.html"><IMG SRC ="next_motif.gif" ALT="Next"></A>
</BODY>
</HTML>