You cannot do this in standard Prolog. However, SWI-Prolog used to support user definitions of arithmetic functions but that feature is, I believe, deprecated in recent releases. Check the documentation. A possible alternative is to take advantage of the term-expansion mechanism that several Prolog systems (including SWI-Prolog) define and goal-expand is/2
goals to deal with calls that make use of user-defined arithmetic functions. Something like:
goal_expansion(X is Expression, X is ExpandedExpression) :-
% traverse and transform Expression
But remember that goal_expansion/2
is called repeatedly until a fix-point is reached. So, be aware of endless loops resulting from trying to expand an already expanded arithmetic expression. One way to solve it is to cache the results of the expansion using a dynamic predicate that is checked when calling goal_expansion/2
. The caching dynamic predicate can be abolished e.g. when the end of the file you're processing:
term_expansion(end_of_file, _) :-
abolish(...), % the argument will be the predicate indicator of the caching predicate
fail.
When expanding end_of_file
is advised to fail after performing whatever actions are necessary as there could be other (orthogonal) expansions also relying on the expansion of end_of_file
.