2.5 Examples (version 2)
AllApplicationManualNameSummaryHelp

  • Documentation
    • Reference manual
    • Packages
      • A C++ interface to SWI-Prolog
        • A C++ interface to SWI-Prolog (Version 2)
          • Examples (version 2)
            • Hello(World) (version 2)
            • Adding numbers (version 2)
            • Average of solutions (version 2)

2.5.2 Adding numbers (version 2)

This example shows arithmetic using the C++ interface, including unification, type-checking, and conversion. The predicate add/3 adds the two first arguments and unifies the last with the result.

PREDICATE(add, 3)
{ return A3.unify_integer(A1.as_long() + A2.as_long());
}

You can use your own variable names instead of A1, A2, etc.:

PREDICATE(add, 3)  // add(+X, +Y, +Result)
{ PlTerm x(A1);
  PlTerm y(A2);
  PlTerm result(A3);
  return result.unify_integer(x.as_long() + y.as_long());
}

The as_long() method for a PlTerm performs a PL_get_long_ex() and throws a C++ exception if the Prolog argument is not a Prolog integer or float that can be converted without loss to a long. The unify_integer() method of PlTerm is defined to perform unification and returns true or false depending on the result.

?- add(1, 2, X).

X = 3.
?- add(a, 2, X).
[ERROR: Type error: `integer' expected, found `a']
   Exception: (  7) add(a, 2, _G197) ?