A shelf is an object with multiple slots whose contents survive backtracking. The content of each slot can be set and retrieved individually, or the whole shelf can be retrieved as a term.
Shelves are referred to by handle, not by name, so they make it easy to write robust, reentrant code. A shelf disappears when the system backtracks over its creation, when the shelf handle gets garbage collected, or when it is explicitly destroyed.
When using shelf_create/3, ShelfSpec determines the number of slots on the shelf, and all slots get initialized identically with the value SlotInit.
% finding the sum and maximum of data/1 facts:
data(2).
data(9).
data(3).
data(5).
data(7).
sum_and_max(Sum, Max) :-
shelf_create(agg/2, 0, Shelf),
(
data(X),
shelf_get(Shelf, 1, OldMax),
( X > OldMax -> shelf_set(Shelf, 1, X) ; true ),
shelf_get(Shelf, 2, OldSum),
NewSum is OldSum + X,
shelf_set(Shelf, 2, NewSum),
fail
;
shelf_get(Shelf, 0, agg(Max, Sum))
),
shelf_abolish(Shelf).