• Places
    • Home
    • Graphs
    • Prefixes
  • Admin
    • Users
    • Settings
    • Plugins
    • Statistics
  • CPACK
    • Home
    • List packs
    • Submit pack
  • Repository
    • Load local file
    • Load from HTTP
    • Load from library
    • Remove triples
    • Clear repository
  • Query
    • YASGUI SPARQL Editor
    • Simple Form
    • SWISH Prolog shell
  • Help
    • Documentation
    • Tutorial
    • Roadmap
    • HTTP Services
  • Login

1.7 Examples
All Application Manual Name SummaryHelp

  • Documentation
    • Reference manual
    • Packages
      • A C++ interface to SWI-Prolog
        • A C++ interface to SWI-Prolog
          • Examples
            • Hello(World)
            • Adding numbers
            • Average of solutions - calling a Prolog goal

1.7.2 Adding numbers

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) ?

ClioPatria (version V3.1.1-51-ga0b30a5)