2.6.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()); }
or more compactly:
PREDICATE(add, 3) // add(+X, +Y, +Result) { auto x = A1, y = A2, 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) ?