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 is unknown. The following steps show how to define this predicate in C and make it callable from Prolog.
#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;
}
}
extern int p();
insert_cpred("p",2,p);