SWI-Prolog -- wrap_predicate/4

Did you know ... Search Documentation:
SWI-Prolog owl logo Predicate wrap_predicate/4
wrap_predicate(:Head, +Name, -Wrapped, +Body) is det
Wrap the predicate referenced by Head using Body. Subsequent calls to Head call the given Body term. Body may call the original definition through Wrapped. Wrapped is a term of the shape below, where Closure is an opaque blob.
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.
Tags are associated to your profile if you are logged in
Tags:
Peter Ludemann said (2023年08月27日T18:52:16):0 upvotes 0 0 downvotes
Picture of user Peter Ludemann.

An example of using wrap_predicate/4 to compute 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, G),
 Gcd is G.
login to add a new annotation post.

AltStyle によって変換されたページ (->オリジナル) /