Example:


\begin{picture}(350,1)(0,0)
\put (0,0){\framebox{(}350,1)}
\end{picture}

Consider the Prolog predicate:

      :-mode p(+,?).
      p(a,f(1)).
      p(b,[1]).
      p(c,1.2).
where the first argument is given, and the second argument is unknown. The following steps show how to define this predicate in C, and how to make it callable from Prolog.

Step 1
. Write a C function to implement the predicate. The following shows a sample:
#include "bprolog.h"

p(){
  TERM a1,a2,a,b,c,f1,l1,f12;
  char *name_ptr;
  
  /*   prepare Prolog terms */
  a1 = bp_get_call_arg(1,2);  /* first argument */
  a2 = bp_get_call_arg(2,2);  /* second argument */
  a = bp_build_atom("a");
  b = bp_build_atom("b");
  c = bp_build_atom("c");
  f1 = bp_build_structure("f",1);  /* f(1) */
  bp_unify(bp_get_arg(1,f1),bp_build_integer(1));
  l1 = bp_build_list();            /* [1] */ 
  bp_unify(bp_get_car(l1),bp_build_integer(1));
  bp_unify(bp_get_cdr(l1),bp_build_nil());
  f12 = bp_build_float(1.2);       /* 1.2 */
  
  /* code for the clauses */
  if (!bp_is_atom(a1)) return BP_FALSE;
  name_ptr = bp_get_name(a1);
  switch (*name_ptr){
  case 'a': 
    return (bp_unify(a1,a) ? bp_unify(a2,f1) : BP_FALSE);
  case 'b': 
    return (bp_unify(a1,b) ? bp_unify(a2,l1) : BP_FALSE);
  case 'c': 
    return (bp_unify(a1,c) ? bp_unify(a2,f12) : BP_FALSE);
  default: return BP_FALSE;
  }
}

\begin{picture}(350,1)(0,0)
\put (0,0){\framebox{(}350,1)}
\end{picture}
Step 2
Insert the following two lines into Cboot() in cpreds.c:
      extern int p();
      insert_cpred("p",2,p);
Step 3
Recompile the system. Now, p/2 is in the group of built-ins in B-Prolog.



Neng-Fa Zhou 2013-01-25