Did you know ... | Search Documentation: |
prolog_wrap.pl -- Wrapping predicates |
This library allows adding wrappers to predicates. The notion of wrappers is known in various languages under several names. For example Logtalk knows these as before methods or after methods and Python has decorators. A SWI-Prolog wrapper is a body term that normally calls the original wrapped definition somewhere.
call(Closure(A1, ...))
Name names the wrapper for inspection using predicate_property/2 or deletion using unwrap_predicate/2. If Head has a wrapper with Name the Body of the existing wrapper is updated without changing the order of the registered wrappers. The same predicate may be wrapped multiple times. Multiple wrappers are executed starting with the last registered (outermost).
The predicate referenced by Head does not need to be defined at the moment the wrapper is installed. If Head is undefined, the predicate is created instead of searched for using e.g., the auto loader.
Registered wrappers are not part of saved states (see qsave_program/2) and thus need to be re-registered, for example using initialization/1.
An example of using wrap_predicate/4 for computing GCD:
:- wrap_predicate(gcd(A,B,Gcd), gcd_wrap, W, gcd_wrap(W, A, B, Gcd)). gcd(X, Y, Gcd), X < Y => gcd(X, Y-X, Gcd). gcd(X, Y, Gcd), X > Y => gcd(Y, X-Y, Gcd). gcd(X, _, Gcd) => Gcd = X. gcd_wrap(call(Closure), X, Y, Gcd) :- functor(Closure, ClosureBlob, 3), X_eval is X, Y_eval is Y, call(ClosureBlob, X_eval, Y_eval, Gcd).
or (less efficient):
gcd_wrap(call(Closure), X, Y, Gcd) :- functor(Closure, ClosureBlob, 3), call(ClosureBlob, X_eval, Y_eval, G), Gcd is G.
Wrappers are enumerated starting with the first registered (innermost) wrapper.