Chapter 1
Overview
On this page
Before we give an overview of the Picat language, let us briefly describe how to use the Picat system. The Picat system provides an interactive programming environment for users to load, debug, and execute programs. Users can start the Picat interpreter with the OS command picat.
picat
Once the interpreter is started, users can type a command line after the prompt Picat>. The help command shows how to use commands, and the halt command terminates the Picat interpreter. Users can also use the picat command to run a program directly as follows:
picat
where (with or without the extension .pi) is the main file name of the program. The program must define a predicate named main/0 or main/1.1 If the command line contains arguments after the file name, then main/1 is executed. Otherwise, if the file name is not followed by any arguments, then main/0 is executed. When main/1 is executed, all of the arguments after the file name are passed to the predicate as a list of strings.
The picat command accepts several options, which specify an initial setting for the interpreter. For example, the option -d starts the interpreter in debug mode, enabling tracing:
picat -d
1.1 Data Types
Picat is a dynamically typed language, in which type checking occurs at runtime. A variable in Picat is a value holder. A variable name is an identifier that begins with a capital letter or an underscore. An attributed variable is a variable that has a map of attribute-value pairs attached to it. A variable is free until it is bound to a value. A value in Picat can be primitive or compound.
A primitive value can be an integer, a real number, or an atom. A character can be represented as a single-character atom. An atom name is either an identifier that begins with a lowercase letter or a single-quoted sequence of characters.
A compound value can be a list in the form [,,] or a structure in the form $(, , ) where stands for a structure name, is called the arity of the structure, and each () is a term which is a variable or a value. The preceding dollar symbol is used to distinguish a structure from a function call. Strings, arrays, maps, sets, and heaps are special compound values. A string is a list of single-character atoms. An array takes the form {,,}, which is a special structure with the name ’{}’. A map is a hash-table represented as a structure that contains a set of key-value pairs. A set is a special map where only keys are used. A heap is a complete binary tree represented as an array. A heap can be a min-heap or a max-heap.
For each data type, Picat provides a set of built-in predicates and functions. For example, the function new_struct() returns a structure. The function new_map() returns a map that initially contains the pairs in list , where each pair has the form . The function new_set() returns a map set that initially contains the elements in list . A map-set is a map in which every key is mapped to the atom not_a_value. The function new_array() returns an n-dimensional array, where each is an integer expression specifying the size of a dimension. An n-dimensional array is a one-dimensional array where the arguments are (n-1)-dimensional arrays.
Example
Picat> V1 = X1, V2 = _ab, V3 = _ % variables
Picat> N1 = 12, N2 = 0xf3, N3 = 1.0e8 % numbers
Picat> A1 = x1, A2 = '_AB', A3 = '' % atoms
Picat> L = [a,b,c,d] % a list
Picat> write("hello" ++ "picat") % strings
[h,e,l,l,o,p,i,c,a,t]
Picat> print("hello" ++ "picat")
hellopicat
Picat> writef("%s", "hello" ++ "picat") % formatted write
hellopicat
Picat> writef("%-5d %5.2f", 2, 2.0) % formatted write
2 2.00
Picat> S = $point(1.0, 2.0) % a structure
Picat> S = new_struct(point, 3) % create a structure
S = point(_3b0, _3b4, _3b8)
Picat> A = {a,b,c,d} % an array
Picat> A = new_array(3) % create an array
A = {_3b0,_3b4,_3b8}
Picat> M = new_map([one = 1, two = 2]) % create a map
M = (map)[two = 2,one = 1]
Picat> M = new_set([one,two,three]) % create a map set
M = (map)[two,one,three]
Picat> X = 1..2..10 % ranges
X = [1,3,5,7,9]
Picat> X = 1..5
X = [1,2,3,4,5]
Picat allows function calls in arguments. For this reason, it requires structures to be preceded with a dollar symbol in order for them to be treated as data. Without the dollar symbol, the command S = point(1.0, 2.0) would call the function point(1.0, 2.0) and bind S to its return value. In order to ensure safe interpretation of meta-terms in higher-order calls, Picat forbids the creation of terms that contain structures with the name ’.’, index notations, array comprehensions, list comprehensions, loops, and higher-order calls. While these constructs cannot be preserved as literal syntax structures, their evaluated results can occur in constructed terms.
For each type, Picat provides a set of built-in functions and predicates. The index notation [], where is a variable that references a compound value and is an expression that evaluates to an integer or an integer range of the form , is a special function that returns a single component (when is an integer) or a slice of components (when is a range) of . The index of the first element of a list or a structure is 1. In order to facilitate type checking at compile time, Picat does not overload arithmetic operators for other purposes, and requires an index expression to be an integer or an integer range.
A list comprehension, which takes the following form, is a special functional notation for creating lists:
[ : in , , , in , ]
where is an expression, each is an iterating pattern, each is an expression that gives a compound value, and the optional conditions , , are callable terms. This list comprehension means that for every tuple of values , , , if the conditions are true, then the value of is added into the list.
An array comprehension takes the following form:
{ : in , , , in , }
It is the same as:
to_array([ : in , , , in , ])
The predicate put() attaches the key-value pair to the map , where is a non-variable term, and is any term. The function get() returns of the key-value pair attached to . The predicate has_key() succeeds iff contains a pair with the given key.
An attributed variable has a map attached to it. The predicate put_attr() attaches the key-value pair to . The function get_attr() returns of the key-value pair attached to .
Example
Picat> integer(5)
yes
Picat> real(5)
no
Picat> var(X)
yes
Picat> X = 5, var(X)
no
Picat> 5 != 2+2
yes
Picat> X = to_binary_string(5)
X = ['1','0','1']
Picat> L = [a,b,c,d], X = L[2]
X = b
Picat> L = [(A,I) : A in [a,b], I in 1..2].
L = [(a,1),(a,2),(b,1),(b,2)]
Picat> put_attr(X, one, 1), One = get_attr(X, one)
One = 1
Picat> S = new_struct(point, 3), Name = name(S), Len = length(S)
S = point(_3b0, _3b4, _3b8)
Name = point
Len = 3
Picat> S = new_array(2, 3), S[1, 1] = 11, D2 = length(S[2])
S = {{11,_93a0,_93a4},{_938c,_9390,_9394}}
D2 = 3
Picat> M = new_map(), put(M, one, 1), One = get(M, one)
One = 1
Picat> M = new_set(), put(M, one), has_key(M, one).
Picat also allows OOP notations, called dot notations, for calling predicates and functions. The notation is the same as , unless is an atom, in which case must be a module qualifier for . The notation , where is an atom, is the same as the call .
Example
Picat> X = 5.to_binary_string()
X = ['1','0','1']
Picat> X = 5.to_binary_string().length
X = 3
Picat> X.put(one, 1), One = X.get(one)
One = 1
Picat> X = math.pi
X = 3.141592653589793
Picat> S = new_struct(point, 3), Name = S.name, Len = S.length
S = point(_3b0, _3b4, _3b8)
Name = point
Len = 3
Picat> S = new_array(2, 3), S[1, 1] = 11, D2 = S[2].length
S = {{11,_93a0,_93a4},{_938c,_9390,_9394}}
D2 = 3
Picat> M = new_map(), M.put(one, 1), One = M.get(one).
One = 1
1.2 Defining Predicates
A predicate call either succeeds or fails, unless an exception occurs. A predicate call can return multiple answers through backtracking. The built-in predicate true always succeeds, and the built-in predicate fail (or false) always fails. A goal is made from predicate calls and statements, including conjunction (), disjunction (), negation (not ), if statements, foreach loops, and while loops.
A predicate is defined with pattern-matching rules. Picat has two types of pattern-matching rules:
The takes 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. For a call , if matches and succeeds, meaning that the condition evaluates to true, 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 . If the used rule is backtrackable, however, the program will backtrack to once fails, meaning that will be rewritten back to , and the next applicable rule will be tried on .
Example
fib(0, F) => F = 1.
fib(1, F) => F = 1.
fib(N, F), N > 1 => fib(N-1, F1), fib(N-2, F2), F = F1+F2.
fib(N, F) => throw $error(wrong_argument, fib, N).
A call matches the head fib(0, F) if the first argument is 0. The second argument can be anything. For example, for the call fib(0, 2), the first rule is applied, since fib(0, 2) matches its head. However, when the body is executed, the call 2 = 1 fails.
The predicate fib/2 can also be defined using an if-statement as follows:
fib(N, F) =>
if (N = 0; N = 1)
F = 1
elseif (N > 1)
fib(N-1, F1), fib(N-2, F2), F = F1+F2
else
throw $error(wrong_argument, fib, N)
end.
An if statement takes the form if () else end.2 The if statement can contain one or more elseif clauses. The else part can be omitted. In that case the else part is assumed to be else true. The built-in throw throws term as an exception.
Example
member(X, [Y|_]) ?=> X = Y.
member(X, [_|L]) => member(X, L).
The pattern [Y|_] matches any non-empty list. The backtrackable rule makes a call nondeterministic, and the predicate can be used to retrieve elements from a list one at a time through backtracking.
Picat> member(X, [1,2,3])
X = 1;
X = 2;
X =
3;
no
After Picat returns an answer, users can type a semicolon immediately after the answer to ask for the next answer. If users only want one answer to be returned from a call, they can use once to stop backtracking.
The version of member that checks if a term occurs in a list can be defined as follows:
membchk(X, [X|_]) => true.
membchk(X, [_|L]) => membchk(X, L).
The first rule is applicable to a call if the second argument is a list and the first argument of the call is identical to the first element of the list.
Horn Clauses
Picat supports Prolog-style Horn clauses. A Horn clause takes the form :- . When is true, the clause can be written as . Let be . The Horn clause can be translated equivalently to the following pattern-matching rule:
?=> , , , .
where the dollar symbols indicate that all of the ’s are terms, rather than function calls.
A predicate definition that consists of Horn clauses can be preceded by an index declaration in the form
where each is either (meaning indexed) or (meaning not indexed). When a predicate defined by Horn clauses is not preceded by an index declaration, Picat automatically generates one for the predicate. For each index pattern (), the compiler generates a version of the predicate that indexes all of the arguments. An index declaration affects the predicate’s efficiency but not its behavior. It is assumed that there is a default version of the predicate that has none of its arguments indexed.
Example
index (+, -) (-, +)
edge(a, b).
edge(a, c).
edge(b, c).
edge(c, b).
For a predicate of Horn clauses, a matching version of the predicate is selected for a call. If no matching version is available, Picat uses the default version. For example, for the call edge(X, Y), if both X and Y are free, then the default version is used.
1.3 Defining Functions
A function call always succeeds with a return value if no exception occurs. Functions are defined with non-backtrackable rules in which the head is an equation =, where is the function pattern in the form and holds the return value. When , the parentheses can be omitted.
Example
fib(0) = F => F = 1.
fib(1) = F => F = 1.
fib(N) = F, N > 1 => F = fib(N-1) + fib(N-2).
qsort([]) = L => L = [].
qsort([H|T]) = L => L = qsort([E : E in T, E =< H]) ++ [H] ++
qsort([E : E in T, E > H]).
A function call never fails and never succeeds more than once. For function calls such as fib(-1) or fib(X), Picat raises an exception.
Picat allows inclusion of function facts in the form (, , )= in function definitions.
Example
fib(0) = 1.
fib(1) = 1.
fib(N) = F, N > 1 => F = fib(N-1) + fib(N-2).
qsort([]) = [].
qsort([H|T]) =
qsort([E : E in T, E =< H]) ++ [H] ++
qsort([E : E in T, E > H]).
Function facts are automatically indexed on all of the input arguments, and hence no index declaration is necessary. Note that while a predicate call with no argument does not need parentheses, a function call with no argument must be followed by parentheses, unless the function is module-qualified, as in math.pi.
The fib function can also be defined as follows:
fib(N) = cond((N = 0; N = 1), 1, fib(N-1)+fib(N-2)).
The conditional expression returns 1 if the condition (N = 0; N = 1) is true, and the value of
fib(N-1)+fib(N-2) if the condition is false.
1.4 Assignments and Loops
Picat allows assignments in rule bodies. An assignment takes the form =, where is either a variable or an access of a component of a compound value in the form […]. When is an access in the form , the component of at index is updated. This update is undone if execution backtracks over this assignment.
Example
test => X = 0, X := X+1, X := X+2, write(X).
In order to handle assignments, Picat creates new variables at compile time. In the above example, at compile time, Picat creates a new variable, say X1, to hold the value of X after the assignment X := X+1. Picat replaces X by X1 on the LHS of the assignment. It also replaces all of the occurrences of X to the right of the assignment by X1. When encountering X1 := X1+2, Picat creates another new variable, say X2, to hold the value of X1 after the assignment, and replaces the remaining occurrences of X1 by X2. When write(X2) is executed, the value held in X2, which is 3, is printed. This means that the compiler rewrites the above example as follows:
test => X = 0, X1 = X+1, X2 = X1+2, write(X2).
Picat supports foreach and while statements for programming repetitions. A foreach statement takes the form
foreach ( in , , , in , )
end
where each iterator, , can be followed by an optional condition . Within each iterator, is an iterating pattern, and is an expression that gives a compound value. The foreach statement means that is executed for every possible combination of values , , that satisfies the conditions , , .3
A while statement takes the form
while ()
end
It repeatedly executes as long as succeeds. A variant of the while loop in the form of
do
while ()
executes one time before testing .
A loop statement forms a name scope. Variables that occur only in a loop, but do not occur before the loop in the outer scope, are local to each iteration of the loop. For example, in the following rule:
p(A) =>
foreach (I in 1 .. A.length)
E = A[I],
writeln(E)
end.
the variables I and E are local, and each iteration of the loop has its own values for these variables.
Example
write_map(Map) =>
foreach ((Key = Value) in Map)
writef("%w = %w\n", Key, Value)
end.
sum_list(L) = Sum => % returns sum(L)
S = 0,
foreach (X in L)
S := S+X
end,
Sum = S.
read_list = List =>
L = [],
E = read_int(),
while (E != 0)
L := [E|L],
E := read_int()
end,
List = L.
The function read_list reads a sequence of integers into a list, terminating when 0 is read. The loop corresponds to the following sequence of recurrences:
= []
= []
= []
= []
List =
Note that the list of integers is in reverse order. If users want a list in the same order as the input, then the following loop can be used:
read_list = List =>
List = L,
E = read_int(),
while (E != 0)
L = [E|T],
L := T,
E := read_int()
end,
L = [].
This loop corresponds to the following sequence of recurrences:
= []
= []
= []
= []
Loop statements are compiled into tail-recursive predicates. For example, the second read_list function given above is compiled into:
read_list = List =>
List = L,
E = read_int(),
p(E, L, Lout),
Lout = [].
p(0, Lin, Lout) => Lout = Lin.
p(E, Lin, Lout) =>
Lin = [E|Lin1],
NE = read_int(),
p(NE, Lin1, Lout).
A list comprehension is first compiled into a foreach loop, and then the loop is compiled into a call to a generated tail-recursive predicate. For example, the list comprehension
List = [(A,X) : A in [a,b], X in 1..2]
is compiled into the following loop:
List = L,
foreach (A in [a,b], X in 1..2)
L = [(A,X)|T],
L := T
end,
L = [].
1.5 Tabling
A predicate defines a relation where the set of facts is implicitly generated by the rules. The process of generating the facts may never end and/or may contain a lot of redundancy. Tabling can prevent infinite loops and redundancy by memorizing calls and their answers. In order to have all calls and answers of a predicate or function tabled, users just need to add the keyword table before the first rule.
Example
table
fib(0) = 1.
fib(1) = 1.
fib(N) = fib(N-1) + fib(N-2).
When not tabled, the function call fib(N) takes exponential time in N. When tabled, however, it takes only linear time.
Users can also give table modes to instruct the system on what answers to table. Mode-directed tabling is especially useful for dynamic programming problems. In mode-directed tabling, a plus-sign (+) indicates input, a minus-sign (-) indicates output, max indicates that the corresponding variable should be maximized, min indicates that the corresponding variable should be minimized, and nt indicates that the corresponding argument is not tabled.4
Example
table(+, +, min)
edit([], [], D) => D = 0.
edit([X|Xs], [X|Ys], D) =>
edit(Xs, Ys, D).
edit(Xs, [Y|Ys], D) ?=> % insert
edit(Xs, Ys, D1),
D = D1+1.
edit([X|Xs], Ys, D) => % delete
edit(Xs, Ys, D1),
D = D1+1.
For a call edit(L1, L2, D), where L1 and L2 are given lists and D is a variable, the rules can generate all facts, each of which contains a different edit distance between the two lists. The table mode table(+, +, min) tells the system to keep a fact with the minimal edit distance.
A tabled predicate can be preceded by both a table declaration and at most one index declaration if it contains facts. The order of these declarations is not important.
1.6 Modules
A module is a source file with the extension .pi. A module begins with a module name declaration and optional import declarations. A module declaration has the form:
where must be the same as the main file name. A file that does not begin with a module declaration is assumed to belong to the global module, and all of the predicates and functions that are defined in such a file are visible to all modules as well as the top-level of the interpreter.
An import declaration takes the form:
where each is a module name. When a module is imported, all of its public predicates and functions will be visible to the importing module. A public predicate or function in a module can also be accessed by preceding it with a module qualifier, as in m.p(), but the module still must be imported.
Atoms and structure names do not belong to any module, and are globally visible. In a module, predicates and functions are assumed to be visible both inside and outside of the module, unless their definitions are preceded by the keyword private.
Example
% in file my_sum.pi
module my_sum.
my_sum(L) = Sum =>
sum_aux(L, 0, Sum).
private
sum_aux([], Sum0, Sum) => Sum = Sum0.
sum_aux([X|L], Sum0, Sum) => sum_aux(L, X+Sum0, Sum).
% in file test_my_sum.pi
module test_my_sum.
import my_sum.
go =>
writeln(my_sum([1,2,3,4])).
The predicate sum_aux is private, and is never visible outside of the module. The following shows a session that uses these modules.
Picat> load("test_my_sum")
Picat> go
10
The command load(File) loads a module file into the system. If the file has not been compiled, then the load command compiles the file before loading it. If this module is dependent on other modules, then the other modules are loaded automatically if they are not yet in the system.5 When a module is loaded, all of its public predicates and functions become visible to the interpreter.
The Picat module system is static, meaning that the binding of normal calls to their definitions takes place at compile time. For higher-order calls, however, Picat may need to search for their definitions at runtime. Several built-in modules are imported by default, including basic, io, math, and sys. For a normal call that is not higher-order in a module, the Picat compiler searches modules for a definition in the following order:
- The implicitly imported built-in modules in the order from basic, math, io to sys.
- The enclosing module of the call.
- The explicitly imported modules in the order that they were imported.
- The global module.
1.7 Higher-order Calls and Anonymous Definitions
1.7.1 Higher-order Call Conventions
A predicate or function is said to be higher-order if it takes calls as arguments. The built-ins call, apply, and find_all are higher-order. The predicate call(, , , ), where is an atom or a structure naming a callable, calls the predicate named by with the arguments that are specified in together with extra arguments , , . The function apply(, , , ) is similar to call, except that apply returns a value. The function findall(, ) returns a list of all possible solutions of call() in the form of . Other higher-order predicates and functions include:
All of these higher-order built-ins are defined in the basic module, except for time/1, time2/1, and time_out/3, which are defined in the sys module. Literal callable terms cannot contain assignments or loops; compiled anonymous bodies can contain both.
The higher-order predicate call call(,
,
,
) and
the function call
apply(,
,
,
),
where
is a variable at compile time, can both be written as
(,
,
). Picat translates this
notation into a call or apply invocation depending on the context. Higher-order calls can also be module-qualified:
m.(,
,
)
invokes the function or predicate defined in module m whose symbol is referenced by
. Within
a term constructor, a higher-order call whose name is a variable is always treated as a function
call.
Example
Picat> S = $member(X), S([1,2,3])
X = 1;
X = 2;
X = 3;
no
Picat> L = findall(X, member(X, [1,2,3])).
L = [1,2,3]
Picat> Z = apply('+', 1, 2)
Z = 3
Picat> F = $'*'(2), Z = F(2)
F = '*'(2)
Z = 4
Picat> F = $'*'(2), Z = $p(F(2))
F = '*'(2)
Z = p(4)
1.7.2 Anonymous Definitions
An anonymous definition creates a function or predicate without giving it a name. An anonymous function, also called a lambda expression, has the form
([A1,A2,...,An] -> Res, B1,B2,...,Bm)
where the bracketed list contains parameter patterns, Res is the return expression, and the remaining goals form the body. The body is executed before the return expression is evaluated. If no body is needed, the comma and body can be omitted. An anonymous predicate has the form
([A1,A2,...,An] => B1,B2,...,Bm)
It has a body but no return expression. Parameters are terms, as in named rule heads, and follow the same pattern-matching conventions. An empty parameter list denotes a definition with no explicit arguments.
Evaluating an anonymous definition creates a callable value, called a closure; its body is executed only when it is invoked. Closures use the same variable-call conventions described above. For example:
Offset = 10,
Add = ([X] -> X+Offset),
Offset := 20,
Y = Add(5), % Y = 15
Print = ([X] => println(X)),
Print(Y)
The function closure captures the value 10 of Offset when it is created. The later assignment to Offset does not change that captured value. The predicate closure prints 15 when invoked.
An anonymous definition forms a name scope, like a foreach loop. Variables that have already occurred in the enclosing scope are global to the definition; variables that first occur inside the definition are fresh locals. In the example, Offset is a context variable of Add, while each parameter X is local to its definition. The body can contain the usual goals, including assignments, conditionals, and loops. An anonymous predicate uses a single => rule; no ?=> form is needed.
The compiler introduces a unique dummy name in the global module and compiles the anonymous definition like a named definition. Its body is compiled in the defining module, preserving that module’s call resolution. The closure can consequently be passed to another module and invoked without importing its defining module. Chapter 10 describes anonymous definitions and higher-order call conventions in detail.
1.7.3 Higher-order Routines
Among the higher-order built-ins, findall is special in that it forms a name scope like a loop. Local variables that occur in a findall call are not visible to subsequent calls in the body or query.
The call apply never returns a partially evaluated function. If the number of arguments does not match the required number, then it throws an exception.
Example
map(F, []) = [].
map(F, [X|Xs]) = [F(X) | map(F, Xs)].
map2(F, [], []) = [].
map2(F, [X|Xs], [Y|Ys]) = [F(X,Y) | map2(F,Xs,Ys)].
fold(F, Acc, []) = Acc.
fold(F, Acc, [H|T]) = fold(F, F(H, Acc), T).
For example, the definitions above accept anonymous functions:
Ys = map(([X] -> X*X),[1,2,3]), % Ys = [1,4,9]
S = fold(([X,A] -> X+A),0,Ys) % S = 14
For named higher-order calls whose targets are unknown at compile time, runtime resolution can require a search of loaded modules. Such calls can incur additional overhead compared with direct calls.
1.8 Constraints
Picat can be used as a modeling and solving language for constraint satisfaction and optimization problems. A constraint program normally poses a problem in three steps: (1) generate variables; (2) generate constraints over the variables; and (3) call solve to find a valuation for the variables that satisfies the constraints, and possibly optimizes an objective function. Picat provides four solver modules, including cp, sat, smt, and mip.
Example
import cp.
go =>
Vars = [S,E,N,D,M,O,R,Y], % generate variables
Vars :: 0..9,
all_different(Vars), % generate constraints
S #!= 0,
M #!= 0,
1000*S+100*E+10*N+D+1000*M+100*O+10*R+E
#= 10000*M+1000*O+100*N+10*E+Y,
solve(Vars), % search
writeln(Vars).
In arithmetic constraints, expressions are treated as data, and it is unnecessary to enclose them with dollar-signs.
The loops provided by Picat facilitate modeling of many constraint satisfaction and optimization problems. The following program solves a Sudoku puzzle:
import cp.
sudoku =>
instance(N, A),
A :: 1..N,
foreach (Row in 1..N)
all_different(A[Row])
end,
foreach (Col in 1..N)
all_different([A[Row,Col] : Row in 1..N])
end,
M = floor(sqrt(N)),
foreach (Row in 1..M, Col in 1..M)
Square = [A[Row1,Col1] :
Row1 in (Row-1)*M+1..Row*M,
Col1 in (Col-1)*M+1..Col*M],
all_different(Square)
end,
solve(A),
foreach (I in 1..N) writeln(A[I]) end.
instance(N, A) =>
N = 9,
A = {{2,_,_,6,7,_,_,_,_},
{_,_,6,_,_,_,2,_,1},
{4,_,_,_,_,_,8,_,_},
{5,_,_,_,_,9,3,_,_},
{_,3,_,_,_,_,_,5,_},
{_,_,2,8,_,_,_,_,7},
{_,_,1,_,_,_,_,_,4},
{7,_,8,_,_,_,6,_,_},
{_,_,_,_,5,3,_,_,8}}.
Recall that variables that occur within a loop, and do not occur before the loop in the outer scope, are local to each iteration of the loop. For example, in the third foreach statement of the sudoku predicate, the variables Row, Col, and Square are local, and each iteration of the loop has its own values for these variables.
1.9 Exceptions
An exception is an event that occurs during the execution of a program that requires special treatment. In Picat, an exception is just a term. The exception interrupt is raised when ctrl-c is typed during a program’s execution. The built-in predicate throw throws .
All exceptions, including those raised by built-ins and interruptions, can be caught by catchers. A catcher is a call in the form: catch(, , ) which is equivalent to , except when an exception is raised during the execution of that unifies with . When such an exception is raised, all of the bindings that have been performed on variables in will be undone, and will be executed to handle the exception.
The call call_cleanup(, ) is equivalent to call(), except that is called when succeeds deterministically (i.e., with no remaining choice point), when fails, or when raises an exception.
1.10 Action Rules
Picat provides action rules for describing event-driven actors. An actor is a predicate call that can be delayed, and can be activated later by events. Each time an actor is activated, an action can be executed. A predicate for actors contains at least one action rule in the form:
=>
where is an actor pattern, is an optional condition, is a non-empty set of event patterns separated by ’,’, and is an action. For an actor and an event, an action rule is said to be applicable if the actor matches and is true. A predicate for actors cannot contain backtrackable rules.
An event channel is an attributed variable to which actors can be attached, and through which events can be posted to actors. A channel has four ports: ins, bound, dom, and any. An event pattern in specifies the port to which the actor is attached. The event pattern ins() attaches the actor to the ins-port of channel , and the actor will be activated when is instantiated. The event pattern event(, ) attaches the actor to the dom-port of channel . The built-in post_event(, ) posts an event term to the dom-port of channel . After an event is posted to a port of a channel, the actors attached to that port are activated. For an activated actor, the system searches for an applicable rule and executes the rule body if it finds one. After execution, the actor is suspended, waiting to be activated again by other events. Picat does not provide a built-in for detaching actors from channels. An actor fails if no rule is applicable to it when it is activated or the body of the applied rule fails. An actor becomes a normal call once a normal non-backtrackable rule is applied to it.
Example
echo(X, Flag), var(Flag), {event(X,T)} => writeln(T).
echo(_X, _Flag) => writeln(done).
foo(Flag) => Flag = 1.
When a call echo(X, Flag) is executed, where Flag is a variable, it is attached to the dom-port of X as an actor. The actor is then suspended, waiting for events posted to the dom-port. For this actor definition, the command
echo(X, Flag), post_event(X, hello), post_event(X, picat).
prints out hello followed by picat. If the call foo(Flag) is inserted before the second call to post_event, then var(Flag) fails when the actor is activated the second time, causing the second rule to be applied to the actor. Then, the output will be hello followed by done. Note that events are not handled until a non-inline call is executed. Replacing foo(Flag) by Flag = 1 will result in a different behavior because Flag = 1 is an inline call.
1.11 Prebuilt Maps
Picat has three kinds of prebuilt maps: heap maps, global maps, and table maps. Prebuilt heap maps are created on the heap immediately after the system is started. The built-in function get_heap_map() returns the heap map that is associated with , where must be a ground term. If no heap map is associated with , then this function establishes an association between and an unused heap map, and returns the map. A heap map is like a normal map. Users use put to add key-value pairs into the map. Users use get to retrieve a value that is associated with a key in the map. Changes made to a heap map since a choice point are undone when execution backtracks to that choice point. The built-in function get_heap_map() returns the heap map that is associated with a system-generated default identifier. There are an unlimited number of prebuilt heap maps.
Global maps are created in the global area when the Picat system is started. The built-in function get_global_map() returns the global map that is associated with , where must be a ground term. If no global map is associated with , then this function establishes an association between and an unused global map, and returns the map. A big difference between a global map and a heap map is that changes to the global map are not undone upon backtracking. When a key-value pair is added into the global map, the variables in the value term are numbered before they are copied to the global area. If the value term contains attributed variables, then the attributes of the variables are not copied, and are therefore lost. When retrieving a value that is associated with a key, the value term in the global area is copied back to the heap after all of the numbered variables are unnumbered. The built-in function get_global_map() returns the global map that is associated with a system-generated default identifier. The number of prebuilt global maps is 97, and the system halts if a program requests more than 97 global maps.
Table maps are created in the table area when the Picat system is started. The built-in function get_table_map() returns the table map that is associated with , where must be a ground term. If no table map is associated with , then this function establishes an association between and an unused table map, and returns the map. Like the global map, changes to a table map are not undone upon backtracking. Unlike the global map, however, keys and values are hash-consed so that common ground sub-terms are not replicated in the table area. The built-in function get_table_map() returns the table map that is associated with a system-generated default identifier. The number of prebuilt table maps is 97, and the system halts if a program requests more than 97 table maps.
The advantage of using prebuilt maps is that data can be accessed everywhere without being passed as arguments, and the disadvantage is that it affects locality of data and thus the readability of programs. In tabled programs, using prebuilt maps is discouraged because it may cause unanticipated effects.
Example
go ?=>
get_heap_map(h1).put(one, 1),
get_global_map(g1).put(one, 1),
get_table_map(t1).put(one, 1),
fail.
go =>
if (get_heap_map(h1).has_key(one))
writef("heap map h1 has key%n")
else
writef("heap map h1 has no key%n")
end,
if (get_global_map(g1).has_key(one))
writef("global map g1 has key%n")
else
writef("global map g1 has no key%n")
end,
if (get_table_map(t1).has_key(one))
writef("table map t1 has key%n")
else
writef("table map t1 has no key%n")
end.
For the call go, the output is:
heap map h1 has no key
global map g1 has key
table map t1 has key
The fail call in the first rule causes execution to backtrack to the second rule. After backtracking, the pair added to the heap map by the first rule is lost, but the pair added to the global map and the pair added to the table map remain.
1.12 Programming Exercises
Project Euler (projecteuler.net) is an excellent platform for practicing programming and problem solving skills. You can find Picat solutions to some of the problems at picat-lang.org/projects.html. Select five problems from the Project Euler problem set for which no solutions have been posted, and write a program in Picat for each of them.
1This document occasionally uses the notation when referring to predicates and functions. When this notation is used, it refers to the predicate or function that is called , which has arguments.
2Picat also accepts Prolog-style if-then-else in the form (If -> Then; Else). It will issue a syntax warning if the else-part is missing.
3The condition break() terminates the loop when is true.
4An ntargument can carry some information that is dependent on the input arguments but useful for the computation.
5Dependent modules must be in a path that is specified by the environment variable PICATPATH, unless their source files are located at the importing source file’s directory.