Chapter 7

Tabling

On this page

The Picat system is a term-rewriting system. For a predicate call, Picat selects a matching rule and rewrites the call into the body of the rule. For a function call C, Picat rewrites the equation C = X where X is a variable that holds the return value of C. Due to the existence of recursion in programs, the term-rewriting process may never terminate. Consider, for example, the following program:

    reach(X, Y) ?=> edge(X, Y).
    reach(X, Y) => reach(X, Z), edge(Z, Y).

where the predicate edge defines a relation, and the predicate reach defines the transitive closure of the relation. For a query such as reach(a, X), the program never terminates due to the existence of left-recursion in the second rule. Even if the rule is converted to right-recursion, the query may still not terminate if the graph that is represented by the relation contains cycles.

Another issue with recursion is redundancy. Consider the following problem: Starting in the top left corner of an N × N grid, one can either go rightward or downward. How many routes are there through the grid to the bottom right corner? The following gives a program in Picat for the problem:

    route(N, N, _Col) = 1.
    route(N, _Row, N) = 1.
    route(N, Row, Col) = 
        route(N, Row+1, Col)+route(N, Row, Col+1).

The function call route(20, 1, 1) returns the number of routes through a 20×20 grid. The function call route(N, 1, 1) takes exponential time in N, because the same function calls are repeatedly spawned during the execution, and are repeatedly resolved each time that they are spawned.

7.1 Table Declarations

Tabling is a memoization technique that can prevent infinite loops and redundancy. The idea of tabling is to memoize the answers to subgoals and use the answers to resolve their variant descendants. In Picat, in order to have all of the calls and answers of a predicate or function tabled, users just need to add the keyword table before the first rule.

Example

    table
    reach(X, Y) ?=> edge(X, Y).
    reach(X, Y) => reach(X, Z), edge(Z, Y).

    table
    route(N, N, _Col) = 1.
    route(N, _Row, N) = 1.
    route(N, Row, Col) = route(N, Row+1, Col)
                         + route(N, Row, Col+1).

With tabling, all queries to the reach predicate are guaranteed to terminate, and the function call route(N, 1, 1) takes only N2 time.

For some problems, such as planning problems, it is infeasible to table all answers, because there may be an infinite number of answers. For some other problems, such as those that require the computation of aggregates, it is a waste to table non-contributing answers. Picat allows users to provide table modes to instruct the system about which answers to table. For a tabled predicate, users can give a table mode declaration in the form (M1 , M2 , … ,Mn), where each Mi is one of the following:

The last mode Mn can be nt, which indicates that the argument is not tabled. Two types of data can be passed to a tabled predicate as an nt argument: (1) global data that are the same for all calls of the predicate, and (2) data that are functionally dependent on the input arguments.

An argument with the mode max, min, mmax or mmin is called an objective argument. Only one argument can be an objective to be optimized. As an objective argument can be a compound value, this limit is not essential, and users can still specify multiple objective variables to be optimized. When the table mode max or min is provided, Picat tables only one optimal answer for the same input arguments. When the table mode mmax or mmin is provided, Picat tables all optimal answers for the same input arguments. Input arguments are assumed to be ground. Output arguments, including objective arguments, are assumed to be variables.

Example

    table(+, +, -, min)
    sp(X, Y, Path, W) ?=>
        Path = [(X,Y)],
        edge(X, Y, W).
    sp(X, Y, Path, W) =>
        Path = [(X,Z)|Path1],
        edge(X, Z, Wxz),
        sp(Z, Y, Path1, W1),
        W = Wxz+W1.

The predicate edge(X, Y, W) specifies a weighted directed graph, where W is the weight of the edge between node X and node Y. The predicate sp(X, Y, Path, W) states that Path is a path from X to Y with the minimum weight W. Note that whenever the predicate sp/4 is called, the first two arguments must always be instantiated. For each pair, the system stores only one path with the minimum weight. When the mode min is replaced with mmin, the system stores all paths with the minimum weight.

The following program finds a shortest path among those with the minimum weight for each pair of nodes:

    table (+, +, -, min)
    sp(X, Y, Path, WL) ?=>
        Path = [(X,Y)],
        WL = (Wxy, 1),
        edge(X, Y, Wxy).
    sp(X, Y, Path, WL) =>
        Path = [(X,Z)|Path1],
        edge(X, Z, Wxz),
        sp(Z, Y, Path1, WL1),
        WL1 = (Wzy, Len1),
        WL = (Wxz+Wzy, Len1+1).

For each pair of nodes, the pair of variables (W, Len) is minimized, where W is the weight, and Len is the length of a path. The built-in function compare_terms(T1, T2 ) is used to compare answers. Note that the order is important. If the term were (Len, W), then the program would find a shortest path, breaking a tie by selecting one with the minimum weight.

The tabling system is useful for offering dynamic programming solutions for planning problems. The following shows a tabled program for general planning problems:

    table (+, -, min)
    plan(S, Plan, Len), final(S) => Plan = [], Len = 0.
    plan(S, Plan, Len) =>
        action(Action, S, S1),
        plan(S1, Plan1, Len1),
        Plan = [Action|Plan1],
        Len = Len1+1.

The predicate action(Action, S, S1) selects an action and performs the action on state S to generate another state, S1. Again, by replacing min with mmin, the predicate plan can be employed to generate all optimal plans.

Example

The program shown in Figure 7.1 solves the Farmer’s problem: The farmer wants to get his goat, wolf, and cabbage to the other side of the river. His boat isn’t very big, and it can only carry him and either his goat, his wolf, or his cabbage. If he leaves the goat alone with the cabbage, then the goat will gobble up the cabbage. If he leaves the wolf alone with the goat, then the wolf will gobble up the goat. When the farmer is present, the goat and cabbage are safe from being gobbled up by their predators.

    go =>
        S0 = [s,s,s,s],
        plan(S0, Plan, _),
        writeln(Plan).

    table (+, -, min)
    plan([n,n,n,n], Plan, Len) => Plan = [], Len = 0.
    plan(S, Plan, Len) =>
        Plan = [Action|Plan1],
        action(S, S1, Action),
        plan(S1, Plan1, Len1),
        Len = Len1+1.
    
    action([F,F,G,C], S1, Action) ?=>
        Action = farmer_wolf,
        opposite(F, F1),
        S1 = [F1,F1,G,C],
        not unsafe(S1).
    action([F,W,F,C], S1, Action) ?=>
        Action = farmer_goat,
        opposite(F, F1),
        S1 = [F1,W,F1,C],
        not unsafe(S1).
    action([F,W,G,F], S1, Action) ?=>
        Action = farmer_cabbage,
        opposite(F, F1),
        S1 = [F1,W,G,F1],
        not unsafe(S1).
    action([F,W,G,C], S1, Action) ?=>
        Action = farmer_alone,
        opposite(F, F1),
        S1 = [F1,W,G,C],
        not unsafe(S1).

    index (+, -) (-, +)
    opposite(n, s).
    opposite(s, n).

    unsafe([F,W,G,_C]), W == G, F !== W => true.
    unsafe([F,_W,G,C]), G == C, F !== G => true.

Figure 7.1: A program for the Farmer’s problem.

7.2 The Tabling Mechanism

The Picat tabling system employs the so-called linear tabling mechanism, which computes fixpoints by iteratively evaluating looping subgoals. The system uses a data area, called the table area, to store tabled subgoals and their answers. The table area can be initialized with the following built-in predicate:

This predicate clears the table area. It’s the user’s responsibility to ensure that no data in the table area are referenced by any part of the application.

Linear tabling relies on the following three primitive operations to access and update the table area.

Subgoal lookup and registration:

This operation is used when a tabled subgoal is encountered during execution. It looks up the subgoal table to see if there is a variant of the subgoal. If not, it inserts the subgoal (termed a pioneer or generator) into the subgoal table. It also allocates an answer table for the subgoal and its variants. Initially, the answer table is empty. If the lookup finds that there already is a variant of the subgoal in the table, then the record that is stored in the table is used for the subgoal (called a consumer). Generators and consumers are handled differently. In linear tabling, a generator is resolved using rules, and a consumer is resolved using answers; a generator is iterated until the fixpoint is reached, and a consumer fails after it exhausts all of the existing answers.

Answer lookup and registration:

This operation is executed when a rule succeeds in generating an answer for a tabled subgoal. If a variant of the answer already exists in the table, then it does nothing; otherwise, it inserts the answer into the answer table for the subgoal, or it tables the answer according to the mode declaration. Picat uses the lazy consumption strategy (also called the local strategy). After an answer is processed, the system backtracks to produce the next answer.

Answer return:

When a consumer is encountered, an answer is returned immediately, if an answer exists. On backtracking, the next answer is returned. A generator starts consuming its answers after it has exhausted all of its rules. Under the lazy consumption strategy, a top-most looping generator does not return any answer until it is complete.