Chapter 4
Predicates and Functions
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
=>.
?=>.
Picat also supports Prolog-style Horn clauses and Definite Clause Grammar (DCG) rules for predicate definitions. A Horn clause takes the form:
:-.
which can be written as
.
if is true. A DCG rule takes the form:
-->.
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 is a pattern in the form , where is called the predicate name, and is called the arity. When , the parentheses can be omitted. The condition , which is an optional goal, specifies a condition under which the rule is applicable. cannot succeed more than once. The compiler converts to once if it would otherwise be possible for to succeed more than once.
For a call , if matches the pattern and is true, then the rule is said to be applicable to . When applying a rule to call , Picat rewrites into . If the used rule is non-backtrackable, then the rewriting is a commitment, and the program can never backtrack to . However, if the used rule is backtrackable, then the program will backtrack to once fails, meaning that will be rewritten back to , and the next applicable rule will be tried on .
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 is an equation =, where is called the function name, and is an expression that gives the return value. Functions are defined with non-backtrackable rules only.
For a function call , if matches the pattern and is true, then the rule is said to be applicable to . When applying a rule to call , Picat rewrites the equation = into (, =), where is a newly introduced variable that holds the return value of .
Picat allows inclusion of function facts in the form (, , )= in function definitions. The function fact (, , )= is shorthand for the rule:
(, , )= =>
= Exp .
where 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*X+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 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 and a term , term matches pattern if is identical to , or if can be made identical to by instantiating ’s variables. Note that variables in the term do not get instantiated after the pattern matching. If term is more general than pattern , 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 @, where is a new variable in the rule, and is a non-variable term. The as-pattern @ is the same as in pattern matching, but after pattern matching succeeds, is made to reference the term that matched . 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:
- true: This goal is always true.
- fail: This goal is always false. When fail occurs in a condition, the condition is false, and the rule is never applicable. When fail occurs in a body, it causes execution to backtrack.
- false: This goal is the same as fail.
- : This goal is a predicate call. The arguments are evaluated in the given order, and the resulting call is resolved using the rules in the predicate . If the call succeeds, then variables in the call may get instantiated. Many built-in predicates are written in infix notation. For example, X = Y is the same as ’=’(X, Y).
- , : This goal is a conjunction of goal and goal . It is resolved by first resolving , and then resolving . The goal is true if both and are true. Note that the order is important: (, ) is in general not the same as (, ).
- : This is the same as (, ).
- ; : This goal is a disjunction of goal and goal . It is resolved by first resolving . If is true, then the disjunction is true. If is false, then is resolved. The disjunction is true if is true. The disjunction is false if both and are false. Note that a disjunction can succeed more than once. Note also that the order is important: (; ) is generally not the same as (; ).
- : This is the same as (; ).
- not : This goal is the negation of . It is false if is true, and true if is false. Note a negation goal can never succeed more than once. Also note that no variables can get instantiated, no matter whether the goal is true or false.
- ' + : This is the same as not .
- once : This goal is the same as , but can never succeed more than once.
-
repeat: This predicate is defined as follows:
repeat ?=> true. repeat => repeat.The repeat predicate is often used to describe failure-driven loops. For example, the query
repeat, writeln(a), failrepeatedly outputs ’a’ until ctrl-c is typed.
-
if: An if statement takes the form
if ()
elseif ()
elseif ()
else
endwhere the elseif and else clauses are optional. If the else clause is missing, then the else goal is assumed to be true. For the if statement, Picat finds the first condition that is true. If such a condition is found, then the truth value of the if statement is the same as . If none of the conditions is true, then the truth value of the if statement is the same as . Note that no condition can succeed more than once.1
- throw : This predicate throws the term . This predicate will be detailed in Chapter 6 on Exceptions.
- !: This special predicate, called a cut, is provided for controlling backtracking. A cut in the body of a rule has the effect of removing the choice points, or alternative rules, of the goals to the left of the cut.
- Loops: Picat has three types of loop statements: foreach, while, and do-while. A loop statement is true if and only if every iteration of the loop is true. The details of loops are given in Chapter 5.
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 is not enclosed in parentheses, then it must be followed by the keyword then.