next up previous index
Next: Non-logical Variables Up: Non-logical Storage and References Previous: Shelves   Index

Stores

A store is an anonymous object which can be used to store information across failures. A typical application is aggregating information across multiple solutions. Note that, if it is not necessary to save information across backtracking, the use of the library(hash) are more appropriate and efficient than the facilities described here.

A store is a hash table which can store arbitrary terms under arbitrary ground keys. Modifications of a store, as well as the entries within it, survive backtracking. The basic operations on stores are entering and looking up information under a key, or retrieving the store contents as a whole.

Stores come in two flavours: anonymous stores are created with store_create/1 and referred to by handle, while named stores are created with a store/ 1 declaration and referred to by their name within a module. If possible, anonymous stores should be preferred because they make it easier to write robust, reentrant code. For example, an anonymous store automatically disappears when the system backtracks over its creation, or when the store handle gets garbage collected. Named stores, on the other hand, must be explicitly destroyed in order to free the associated memory.

Data is entered into a store using store_set/3 and retrieved using store_get/3. It is possible to retrieve all keys with stored_keys/2 or the full contents of the table with stored_keys_and_values/2. Entries can be deleted via store_delete/2 or store_erase/1.

The following example computes how many solutions of each kind a goal has. We use an anonymous store into which we enter counter values, using the solution term as the key to distinguish the different counters:

    solutions_profile(Sol, Goal, Profile) :-
        store_create(Store),
        (
            call(Goal),
            ( store_get(Store, Sol, Old) ->
                New is Old + 1,
                store_set(Store, Sol, New)
            ;
                store_set(Store, Sol, 1)
            ),
            fail
        ;
            stored_keys_and_values(Store, Profile)
        ).
Running this code produces for example:
    ?- solutions_profile(X, member(X, [a, b, c, b, a, b]), R).
    X = X
    R = [a - 2, b - 3, c - 1]
    Yes (0.00s cpu)


next up previous index
Next: Non-logical Variables Up: Non-logical Storage and References Previous: Shelves   Index
Warwick Harvey
2004-08-07