Chapter 4

Predicates and Functions

On this page

In Picat, predicates and functions are defined with rules. Each rule ends with a dot (.) followed by a whitespace character or the end of the file.

Picat has two types of pattern-matching rules: the non-backtrackable rule

   Head,Cond=>Body.

and the backtrackable rule

   Head,Cond?=>Body.

Picat also supports Prolog-style Horn clauses and Definite Clause Grammar (DCG) rules for predicate definitions. A Horn clause takes the form:

   Head:-Body.

which can be written as

   Head.

if Body is true. A DCG rule takes the form:

   Head-->Body.

A predicate definition that consists of Horn clauses can be preceded by an index declaration, as described in Section 1.2. Picat converts Horn clauses and DCG rules into pattern-matching rules.

4.1 Predicates

A predicate defines a relation, and can have zero, one, or multiple answers. Within a predicate, the Head is a pattern in the form p(t1,…,tn), where p is called the predicate name, and n is called the arity. When n = 0, the parentheses can be omitted. The condition Cond, which is an optional goal, specifies a condition under which the rule is applicable. Cond cannot succeed more than once. The compiler converts Cond to once Cond if it would otherwise be possible for Cond to succeed more than once.

For a call C, if C matches the pattern p(t1 ,…,tn) and Cond is true, then the rule is said to be applicable to C. When applying a rule to call C, Picat rewrites C into Body. If the used rule is non-backtrackable, then the rewriting is a commitment, and the program can never backtrack to C. However, if the used rule is backtrackable, then the program will backtrack to C once Body fails, meaning that Body will be rewritten back to C, and the next applicable rule will be tried on C.

A predicate is said to be deterministic if it is defined with non-backtrackable rules only, nondeterministic if at least one of its rules is backtrackable, and globally deterministic if it is deterministic and all of the predicates in the bodies of the predicate’s rules are also globally deterministic. A deterministic predicate that is not globally deterministic can still have more than one answer.

Example

    append(Xs, Ys, Zs) ?=> Xs = [], Ys = Zs.
    append(Xs, Ys, Zs) =>
        Xs = [X|XsR],
        Zs = [X|ZsR],
        append(XsR, Ys, ZsR).

    min_max([H], Min, Max) => Min = H, Max = H.
    min_max([H|T], Min, Max) => 
        min_max(T, MinT, MaxT), 
        Min = min(MinT, H),
        Max = max(MaxT, H).

The predicate append(Xs, Ys, Zs) is true if the concatenation of Xs and Ys is Zs. It defines a relation among the three arguments, and does not assume directionality of any of the arguments. For example, this predicate can be used to concatenate two lists, as in the call

    append([a,b], [c,d], L)

This predicate can also be used to split a list nondeterministically into two sublists, as in the call append(L1, L2, [a,b,c,d]); this predicate can even be called with three free variables, as in the call append(L1, L2, L3).

The predicate min_max(L, Min, Max) returns two values through its arguments. It binds Min to the minimum of list L, and binds Max to the maximum of list L. This predicate does not backtrack. Note that a call fails if the first argument is not a list. Also note that this predicate consumes linear space. A tail-recursive version of this predicate that consumes constant space will be given below.

4.2 Functions

A function is a special kind of predicate that always succeeds with one answer. Within a function, the Head is an equation p(t1 , … , tn )=X, where p is called the function name, and X is an expression that gives the return value. Functions are defined with non-backtrackable rules only.

For a function call C, if C matches the pattern p(t1 ,…,tn) and Cond is true, then the rule is said to be applicable to C. When applying a rule to call C, Picat rewrites the equation C=X′ into (Body, X′ =X), where X′ is a newly introduced variable that holds the return value of C.

Picat allows inclusion of function facts in the form p(t1, …, tn )=Exp in function definitions. The function fact p(t1, …, tn )=Exp is shorthand for the rule:

  p(t1, …, tn )=X => X= Exp.

where X is a new variable.

Although all functions can be defined as predicates, it is preferable to define them as functions for two reasons. Firstly, functions often lead to more compact expressions than predicates, because arguments of function calls can be other function calls. Secondly, functions are easier to debug than predicates, because functions never fail and never return more than one answer.

Example

    qequation(A, B, C) = (R1, R2), 
        D = B*B-4*A*C, 
        D >= 0 
    => 
        NTwoC = -2*C,
        R1 = NTwoC/(B+sqrt(D)),
        R2 = NTwoC/(B-sqrt(D)).

    rev([]) = [].
    rev([X|Xs]) = rev(Xs)++[X].

The function qequation(A, B, C) returns the pair of roots of A*X2 +B*X+C = 0. If the discriminant B*B-4*A*C is negative, then an exception will be thrown.

The function rev(L) returns the reversed list of L. Note that the function rev(L) takes quadratic time and space in the length of L. A tail-recursive version that consumes linear time and space will be given below.

4.3 Patterns and Pattern-Matching

The pattern p(t1,…,tn) in the head of a rule takes the same form as a structure. Function calls are not allowed in patterns. Also, patterns cannot contain index notations, dot notations, ranges, array comprehensions, or list comprehensions. Pattern matching is used to decide whether a rule is applicable to a call. For a pattern P and a term T, term T matches pattern P if P is identical to T, or if P can be made identical to T by instantiating P’s variables. Note that variables in the term do not get instantiated after the pattern matching. If term T is more general than pattern P, then the pattern matching can never succeed.

Unlike calls in many committed-choice languages, calls in Picat are never suspended if they are more general than the head patterns of the rules. A predicate call fails if it does not match the head pattern of any of the rules in the predicate. A function call throws an exception if it does not match the head pattern of any of the rules in the function. For example, for the function call rev(L), where L is a variable, Picat will throw the following exception:

   unresolved_function_call(rev(L)).

A pattern can contain as-patterns in the form V @Pattern, where V is a new variable in the rule, and Pattern is a non-variable term. The as-pattern V @Pattern is the same as Pattern in pattern matching, but after pattern matching succeeds, V is made to reference the term that matched Pattern. As-patterns can avoid re-constructing existing terms.

Example

    merge([], Ys) = Ys.
    merge(Xs, []) = Xs.
    merge([X|Xs], Ys@[Y|_]) = [X|Zs], X < Y => 
        Zs = merge(Xs, Ys). 
    merge(Xs, [Y|Ys]) = [Y|merge(Xs,Ys)].

In the third rule, the as-pattern Ys@[Y|_] binds two variables: Ys references the second argument, and Y references the car of the argument. The rule can be rewritten as follows without using any as-pattern:

    merge([X|Xs], [Y|Ys]) = [X|Zs], X < Y => 
        Zs = merge(Xs, [Y|Ys]). 

Nevertheless, this version is less efficient, because the cons [Y|Ys] needs to be re-constructed.

4.4 Goals

In a rule, both the condition and the body are goals. Queries that the users give to the interpreter are also goals. A goal can take one of the following forms:

4.5 Tail Recursion

A rule is said to be tail-recursive if the last call in the body calls the predicate defined by the rule. The last-call optimization enables last calls to reuse the stack frame of the head predicate if the frame is not protected by any choice points. This optimization is especially effective for tail recursion, because it converts recursion into iteration. Tail recursion runs faster and consumes less memory than non-tail recursion.

The trick to convert a predicate (or a function) into tail recursion is to define a helper that uses an accumulator parameter to accumulate the result. When the base case is reached, the accumulator is returned. At each iteration, the accumulator is updated. Initially, the original predicate (or function) calls the helper with an initial value for the accumulator parameter.

Example

    min_max([H|T], Min, Max) => 
        min_max_helper([H|T], H, Min, H, Max).

    min_max_helper([], CMin, Min, CMax, Max) => 
        Min = CMin, Max = CMax.
    min_max_helper([H|T], CMin, Min, CMax, Max) => 
        min_max_helper(T, min(CMin, H), Min, max(CMax, H), Max).

    rev([]) = [].
    rev([X|Xs]) = rev_helper(Xs, [X]).

    rev_helper([], R) = R.
    rev_helper([X|Xs], R) = rev_helper(Xs, [X|R]).

In the helper predicate min_max_helper(L, CMin, Min, CMax, Max), CMin and
CMax are accumulators: CMin is the current minimum value, and CMax is the current maximum value. When L is empty, the accumulators are returned by the unification calls Min = CMin and Max = CMax. When L is a cons [H|T], the accumulators are updated: CMin changes to min(CMin,H), and CMax changes to max(CMax,H). The helper function rev_helper(L, R) follows the same idea: it uses an accumulator list to hold, in reverse order, the elements that have been scanned. When L is empty, the accumulator is returned. When L is the cons [X|Xs], the accumulator R changes to [X|R].

1If Condi is not enclosed in parentheses, then it must be followed by the keyword then.