Up Next

4.1  Coding External Predicates

External Predicates are C/C++ functions that can be called like predicates from ECLiPSe. Two following extra interface functions are provided for this purpose:
EC_word EC_arg(int i)
returns the i'th argument of the predicate call.

pword ec_arg(int i)

same for C.

int unify(EC_word, EC_word)

unify two pwords. The return code indicates success or failure. Note however, that if attributed variables are involved, their handlers have not been invoked yet (this happens after the external predicate returns).

int EC_word::unify(EC_word)

same as method.

int ec_unify(pword, pword)

same for C.
Apart from that, all functions for constructing, testing and decomposing ECLiPSe data can be used in writing the external predicate (see chapter 3). Here are two examples working with lists, the first one constructing a list in C:
#include "eclipse.h"
int
p_string_to_list()         /* string_to_list(+String, -List) */
{
    pword  list;
    char *s;
    long len;
    int res;

    res = ec_get_string_length(ec_arg(1), &s, &len);
    if (res != PSUCCEED) return res;

    list = ec_nil();    /* build the list backwards */
    while (len--)
        list = ec_list(ec_long(s[len]), list);

    return ec_unify(ec_arg(2), list);
}
The next example uses an input list of integers and sums up the numbers. It is written in C++:
#include "eclipseclass.h"
extern "C" int
p_sumlist()
{
    int res;
    long x, sum = 0;
    EC_word list(EC_arg(1));
    EC_word car,cdr;

    for ( ; list.is_list(car,cdr) == EC_succeed; list = cdr)
    {
        res = car.is_long(&x);
        if (res != EC_succeed) return res;
        sum += x;
    }
    res = list.is_nil();
    if (res != EC_succeed) return res;
    return unify(EC_arg(2), EC_word(sum));
}
The source code of these examples can be found in directory doc/examples within the ECLiPSe installation.


Up Next