\ignore{
\documentstyle[11pt]{report}
\textwidth 13.7cm
\textheight 21.5cm
\newcommand{\myimp}{\verb+ :- +}
\newcommand{\ignore}[1]{}
\def\definitionname{Definition}

\makeindex
\begin{document}

}
\chapter{\label{chapter:overview}Overview}
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\index{debugging}, and execute programs. Users can start the Picat interpreter with the OS command \texttt{picat}\index{\texttt{picat}}.
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> $OSPrompt$ \texttt{picat}
\end{tabbing}
Once the interpreter is started, users can type a command line after the prompt \verb+Picat>+. The \texttt{help}\index{\texttt{help/0}} command shows the usages of commands, and the \texttt{halt}\index{\texttt{halt/0}} command terminates the Picat interpreter. Users can also use the \texttt{picat} command to run a program directly as follows:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> $OSPrompt$ \texttt{picat $File$ $Arg_1$ $Arg_2$ $\ldots$ $Arg_n$}
\end{tabbing}
where $File$ (with or without the extension \texttt{.pi}) is the main file name of the program. The program must define a predicate named \texttt{main/0} or \texttt{main/1}.\footnote{This document occasionally uses the notation $F/N$ when referring to predicates and functions.  When this notation is used, it refers to the predicate or function that is called $F$, which has $N$ arguments.} If the command line contains arguments after the file name, then \texttt{main/1} is executed. Otherwise, if the file name is not followed by any arguments, then \texttt{main/0} is executed. When \texttt{main/1} executed, all of the arguments after the file name are passed to the predicate as a list of strings.

The \texttt{picat} command accepts several options, which specify an initial setting for the interpreter. For example, the option \texttt{-d} starts the interpreter in debug mode, enabling tracing:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> $OSPrompt$ \texttt{picat -d}
\end{tabbing}

\ignore{
The OS command \texttt{picatc}\index{\texttt{picatc}} compiles a file (with extension name \texttt{pi}) and all of its dependent files into bytecode files (with extension name \texttt{qi}), and the OS command \texttt{picate}\index{\texttt{picate}} executes a Picat program as a standalone application.\footnote{The executables \texttt{picatc} and \texttt{picate} will be added later.}
}

\section{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 the underscore. An \emph{attributed variable}\index{attributed variable} is a variable that has a map\index{map} of attribute-value pairs attached to it. A variable is free\index{free variable} until it is bound to a value. A value in Picat can be \emph{primitive}\index{primitive value} or \emph{compound}\index{compound value}. 

A primitive value\index{primitive value} can be an integer\index{integer}, a real number\index{number}, or an atom\index{atom}. A character can be represented as a single-character atom\index{atom}.  An atom\index{atom} name is an identifier that begins with a lower-case letter or a single-quoted sequence of characters. 

A compound value\index{compound value} can be a \emph{list}\index{list} in the form \texttt{[$t_1$,$\ldots$,$t_{n}$]} or a \emph{structure}\index{structure} in the form \texttt{\$$s$($t_1$,$\ldots$,$t_{n}$)} where $s$ stands for a structure\index{structure} name, $n$ is called the \emph{arity}\index{arity} of the structure\index{structure}, and each $t_i$ ($1\le i \le n$) is a \emph{term}\index{term} which is a variable or a value. The preceding dollar symbol is used to distinguish a structure\index{structure} from a function\index{function} call. \emph{Strings}\index{string}, \emph{arrays}\index{array}, \emph{maps}\index{map}, \emph{sets}\index{set}, and \emph{heaps}\index{heap} are special compound values\index{compound value}. A \emph{string}\index{string} is a list\index{list} of single-character atoms\index{atom}. An \emph{array}\index{array} takes the form \texttt{\{$t_1$,$\ldots$,$t_{n}$\}}, which is a special structure\index{structure} with the name \texttt{'\{\}'}. A \emph{map}\index{map} is a hash-table represented as a structure\index{structure} that contains a set of key-value pairs. A \emph{set}\index{set} is a special map where only keys are used.  A \emph{heap}\index{heap} is a complete binary tree represented as an array. A heap can be a \emph{min-heap}\index{min-heap} or a \emph{max-heap}\index{max-heap}.

The function \texttt{new\_struct($Name,IntOrList$)}\index{\texttt{new\_struct/2}} returns a structure\index{structure}. The function \texttt{new\_map($S$)}\index{\texttt{new\_map/1}} returns a map\index{map} that initially contains the pairs in list $S$, where each pair has the form $Key\ =\ Val$. The function \texttt{new\_set($S$)}\index{\texttt{new\_set/1}} returns a \emph{map set} that initially contains the elements in list $S$. A \emph{map-set} \index{map-set} is a map in which every key is mapped to the atom \texttt{not\_a\_value}. The function \texttt{new\_array($I_1,I_2,\ldots,I_{n}$)}\index{\texttt{new\_array}} returns an n-dimensional array\index{array}, where each $I_i$ is an integer expression specifying the size of a dimension. An n-dimensional array\index{array} is a one-dimensional array\index{array} where the arguments are (n-1)-dimensional arrays\index{array}. 

\subsection*{Example}
\begin{verbatim}
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]
\end{verbatim}

Picat allows function\index{function} calls in arguments. For this reason, it requires structures\index{structure} to be preceded with a dollar symbol in order for them to be treated as data. Without the dollar symbol, the command \texttt{S = point(1.0,2.0)} would call the function \texttt{point(1.0,2.0)} and bind \texttt{S} to its return value. In order to ensure safe interpretation of meta-terms in higher-order calls\index{higher-order call}, Picat forbids the creation of terms\index{term} that contain structures\index{structure} with the name \texttt{'.'}, index notations, array comprehensions, list comprehensions, and loops.

For each type, Picat provides a set of built-in functions\index{function} and predicates\index{predicate}. The index notation \texttt{$X$[$I$]}, where $X$ references a compound value\index{compound value} and $I$ is an integer expression or a range in the form $l..u$, is a special function that returns a single component (when $I$ is an integer) or a list of components (when $I$ is a range) of $X$. The index of the first element of a list\index{list} or a structure\index{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\index{integer} or an integer range.

A list comprehension\index{list comprehension}, which takes the following form, is a special functional notation for creating lists:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> \texttt{[$T$ : $E_1$ \texttt{in} $D_1$, $Cond_1$, $\ldots$, $E_n$ in $D_n$, $Cond_n$]} 
\end{tabbing}
where $T$ is an expression, each $E_i$ is an iterating pattern\index{iterator}, each $D_i$ is an expression that gives a compound value\index{compound value}, and the optional conditions $Cond_1$,$\ldots$,$Cond_n$  are callable terms\index{term}. This list comprehension\index{list comprehension} means that for every tuple of values $E_1 \in D_1$, $\ldots$, $E_n \in D_n$, if the conditions are true, then the value of $T$ is added into the list\index{list}.

An array comprehension\index{array comprehension} takes the following form:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> \texttt{\{$T$ : $E_1$ \texttt{in} $D_1$, $Cond_1$, $\ldots$, $E_n$ in $D_n$, $Cond_n$\}} 
\end{tabbing}
It is the same as:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> \texttt{to\_array([$T$ : $E_1$ \texttt{in} $D_1$, $Cond_1$, $\ldots$, $E_n$ in $D_n$, $Cond_n$])} 
\end{tabbing}

The predicate \texttt{put($Map,Key,Val$)}\index{\texttt{put/3}} attaches the key-value pair \texttt{$Key$$=$$Val$} to the map \texttt{$Map$}, where \texttt{$Key$} is a non-variable term\index{term}, and \texttt{$Val$} is any term\index{term}. The function \texttt{get($Map,Key$)}\index{\texttt{get/2}} returns \texttt{$Val$} of the key-value pair \texttt{$Key$$=$$Val$} attached to \texttt{$Map$}. The predicate \texttt{has\_key($Map,Key$)}\index{\texttt{has\_key/2}} returns true iff $Map$ contains a pair with the given key.

An attributed variable\index{attributed variable} has a map\index{map} attached to it. The predicate \texttt{put\_attr($X,Key,Val$)}\index{\texttt{put\_attr/3}} attaches the key-value pair \texttt{$Key$$=$$Val$} to \texttt{$X$}. The function \texttt{get\_attr($X,Key$)}\index{\texttt{get\_attr/2}} returns \texttt{$Val$} of the key-value pair \texttt{$Key$$=$$Val$} attached to \texttt{$X$}. 

\subsection*{Example}
\begin{verbatim}
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)  % attributed var
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).
\end{verbatim}

Picat also allows OOP notations for calling predicates\index{predicate} and functions\index{function}. The notation \texttt{$A_1.f(A_2,\ldots,A_k)$} is the same as \texttt{$f(A_1,A_2,\ldots,A_k)$}, unless $A_1$ is an atom, in which case $A_1$ must be a module qualifier for $f$.  The notation $A.f$, where $f$ is an atom, is the same as the call \texttt{$A.f()$}. 

\subsection*{Example}
\begin{verbatim}
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.14159

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.one.
One = 1
\end{verbatim}

\section{Defining Predicates}
A predicate\index{predicate} call either succeeds or fails, unless an exception\index{exception} occurs. A predicate\index{predicate} call can return multiple answers through backtracking. The built-in predicate \texttt{true}\index{\texttt{true}} always succeeds, and the built-in predicate \texttt{fail}\index{\texttt{fail}} (or \texttt{false}\index{\texttt{false}}) always fails. A \emph{goal}\index{goal} is made from predicate\index{predicate} calls and statements, including conjunction ($A,B$), disjunction ($A;B$), negation (not $A$), if statement\index{if statement}, \texttt{foreach} loops\index{foreach loop}, and \texttt{while} loops\index{while loop}.

A predicate\index{predicate} is defined with pattern-matching rules. Picat has two types of pattern-matching rules:
\begin{itemize}
\item Non-backtrackable rule:\index{non-backtrackable rule} $Head, Cond\ $\verb+=>+$\ Body$.
\item Backtrackable rule:\index{backtrackable rule} $Head, Cond\ $\verb+?=>+$\ Body$.
\end{itemize}
The $Head$ takes the form $p(t_1,\ldots,t_n)$, where $p$ is called the predicate\index{predicate} name, and $n$ is called the arity\index{arity}. When $n = 0$, the parentheses can be omitted. The condition $Cond$, which is an optional goal\index{goal}, specifies a condition under which the rule is applicable. For a call $C$, if $C$ matches $Head$ and $Cond$ succeeds, meaning that the condition evaluates to true, the rule is said to be \emph{applicable} to $C$. When applying a rule to call $C$, Picat rewrites $C$ into $Body$. If the used rule is non-backtrackable\index{non-backtrackable rule}, then the rewriting is a commitment, and the program can never backtrack to $C$. If the used rule is backtrackable\index{backtrackable rule}, however, 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$. 

\subsection*{Example}
\begin{verbatim}
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).
\end{verbatim}

A call matches the head \texttt{fib(0,F)} if the first argument is 0. The second argument can be anything. For example, for the call \texttt{fib(0,2)}, the first rule is applied, since \texttt{fib(0, 2)} matches its head. However, when the body is executed, the call \texttt{2 = 1} fails.  

The predicate \texttt{fib/2} can also be defined using if-statement\index{if statement} as follows:
\begin{verbatim}
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.
\end{verbatim}
An \texttt{if} statement\index{if statement} takes the form \texttt{if ($Cond$) $Goal_1$ else $Goal_2$ end}.\footnote{Picat also accepts Prolog-style if-then-else in the form \texttt{(If -> Then; Else)} and mandates the presence of the else-part.} The goal $Goal_1$ can contain one or more \texttt{elseif} clauses. The \texttt{else} part can be omitted. In that case the else part is assumed to be \texttt{else true}. The built-in \texttt{throw $E$}\index{\texttt{throw/1}} throws term\index{term} $E$ as an exception\index{exception}.

\subsection*{Example}
\begin{verbatim}
member(X,[Y|_]) ?=> X = Y.
member(X,[_|L]) => member(X,L).
\end{verbatim}

The pattern \verb+[Y|_]+ matches any list\index{list}. The backtrackable rule\index{backtrackable rule} makes a call nondeterministic, and the predicate\index{predicate} can be used to retrieve elements from a list\index{list} one at a time through backtracking.
\begin{verbatim}
Picat> member(X,[1,2,3])
X = 1;
X = 2;
X =
3;
no
\end{verbatim}
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 \texttt{once $Call$}\index{\texttt{once/1}} to stop backtracking.

The version of \texttt{member}\index{\texttt{member/2}} that checks if a term\index{term} occurs in a list\index{list} can be defined as follows:
\begin{verbatim}
membchk(X,[X|_]) => true.
membchk(X,[_|L]) => membchk(X,L).
\end{verbatim}
The first rule is applicable to a call if the second argument is a list\index{list} and the first argument of the call is identical to the first element of the list\index{list}.

\subsection*{\label{section:horn}Horn Clauses}
Picat supports Prolog-style Horn clauses\index{Horn clause}\index{Prolog}.\footnote{This feature has been supported since version 3.0.} A Horn clause takes the form $Head$\ :-\ $Body$. When $Body$ is \texttt{true}, the clause can be written as $Head$. Let $Head$ be $p(t_1,\ldots,t_n)$. The Horn clause can be translated equivalently to the following pattern-matching rule:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> $p(V_1,\ldots,V_n)$ \verb+?=>+\ $V_1 = \$t_1$, $\ldots$, $V_n = \$t_n$, $Body$.
\end{tabbing}
where the dollar symbols indicate that all of the $t_i$'s are terms, rather than function calls.

A predicate\index{predicate} definition that consists of Horn clauses can be preceded by an \emph{index declaration}\index{index declaration} in the form
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{index ($M_{11},\ldots,M_{1n}$) $\ldots$ ($M_{m1},\ldots,M_{mn}$)}\index{\texttt{index}}
\end{tabbing}
where each $M_{ij}$ 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 \texttt{($M_{i1},\ldots,M_{in}$)}, the compiler generates a version of the predicate\index{predicate} that indexes all of the $+$ arguments. An index declaration only affects the efficiency, but not the behavior of the predicate. It is assumed that there is a default version of the predicate that has none of its arguments indexed.


\subsection*{Example}
\begin{verbatim}
index (+,-) (-,+)
edge(a,b).
edge(a,c).
edge(b,c).
edge(c,b).
\end{verbatim}
For a predicate of Horn clauses, a matching version of the predicate\index{predicate} is selected for a call. If no matching version is available, Picat uses the default version. For example, for the call \texttt{edge(X,Y)}, if both \texttt{X} and \texttt{Y} are free\index{free variable}, then the default version is used.

\section{Defining Functions}
A function\index{function} call always succeeds with a return value if no exception\index{exception} occurs. Functions\index{function} are defined with non-backtrackable rules\index{non-backtrackable rule} in which the head is an equation $F$\verb+=+$X$, where $F$ is the function\index{function} pattern in the form $f(t_1,\ldots, t_n)$ and $X$ holds the return value. When $n = 0$, the parentheses can be omitted.

\subsection*{Example}
\begin{verbatim}
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]).
\end{verbatim}
A function\index{function} call never fails and never succeeds more than once. For function\index{function} calls such as \texttt{fib(-1)} or \texttt{fib(X)}, Picat raises an exception\index{exception}. 

Picat allows inclusion of \emph{function facts}\index{function fact} in the form {\tt $f$($t_1$,$\ldots$,$t_n$)\verb+=+$Exp$} in function\index{function} definitions. 

\subsection*{Example}
\begin{verbatim}
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]).
\end{verbatim}
Function facts\index{function fact} are automatically indexed on all of the input arguments, and hence no index declaration\index{index declaration} is necessary. Note that while a predicate\index{predicate} call with no argument does not need parentheses, a function\index{function} call with no argument must be followed with parentheses, unless the function\index{function} is module-quantified, as in \texttt{math.pi}.

The \texttt{fib} function can also be defined as follows:\index{\texttt{cond}}
\begin{verbatim}
fib(N) = cond((N = 0; N = 1), 1, fib(N-1)+fib(N-2)).
\end{verbatim}
The conditional expression returns 1 if the condition \texttt{(N = 0; N = 1)} is true, and the value of \\ \texttt{fib(N-1)+fib(N-2)} if the condition is false.

\section{Assignments and Loops}
Picat allows assignments\index{assignment} in rule bodies. An assignment\index{assignment} takes the form $LHS $$:$\verb+=+$ RHS$, where $LHS$ is either a variable or an access of a compound value\index{compound value} in the form \texttt{$X$[\ldots]}. When $LHS$ is an access in the form $X[I]$, the component of $X$ indexed $I$ is updated. This update is undone if execution backtracks over this assignment\index{assignment}.

\subsection*{Example}
\begin{verbatim}
    test => X = 0, X := X+1, X := X+2, write(X).
\end{verbatim}

In order to handle assignments\index{assignment}, Picat creates new variables at compile time.  In the above example, at compile time, Picat creates a new variable, say \texttt{X1}, to hold the value of \texttt{X} after the assignment\index{assignment} \verb-X := X+1-. Picat replaces \texttt{X} by \texttt{X1} on the LHS of the assignment\index{assignment}.  It also replaces all of the occurrences of \texttt{X} to the right of the assignment\index{assignment} by \texttt{X1}.  When encountering \verb-X1 := X1+2-, Picat creates another new variable, say \texttt{X2}, to hold the value of \texttt{X1} after the assignment\index{assignment}, and replaces the remaining occurrences of \texttt{X1} by \texttt{X2}. When \texttt{write(X2)}\index{\texttt{write/1}} is executed, the value held in \texttt{X2}, which is 3, is printed.  This means that the compiler rewrites the above example as follows:
\begin{verbatim}
    test => X = 0, X1 = X+1, X2 = X1+2, write(X2).
\end{verbatim}

Picat supports \texttt{foreach}\index{foreach loop} and \texttt{while}\index{while loop} statements for programming repetitions. A \texttt{foreach}\index{foreach loop} statement takes the form
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{foreach ($E_1$ in $D_1$, $Cond_1$, $\ldots$, $E_n$ in $D_n$, $Cond_n$)}  \\
\> \> $Goal$ \\
\>  \texttt{end} 
\end{tabbing}
where each iterator\index{iterator}, $E_i\ in\ D_i$, can be followed by an optional condition $Cond_i$.  Within each iterator\index{iterator}, $E_i$ is an iterating pattern\index{iterator}, and $D_i$ is an expression that gives a compound value\index{compound value}. The \texttt{foreach}\index{foreach loop} statement means that $Goal$ is executed for every possible combination of values $E_1 \in D_1$, $\ldots$, $E_n \in D_n$ that satisfies the conditions \texttt{$Cond_1$}, $\ldots$, \texttt{$Cond_n$}.\footnote{The condition \texttt{break($Cond$)} terminates the loop when $Cond$ is true.}\index{\texttt{break}}

A while\index{while loop} statement takes the form 
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{while ($Cond$)} \\
\> \> $Goal$  \\
\>  \texttt{end}
\end{tabbing} 
It repeatedly executes $Goal$ as long as $Cond$ succeeds. A variant of the while loop\index{do-while loop} in the form of 
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{do} \\
\> \> $Goal$  \\
\>  \texttt{while ($Cond$)}
\end{tabbing}
executes $Goal$ one time before testing $Cond$.

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\index{scope}, are local\index{local variable} to each iteration of the loop. For example, in the following rule:
\begin{verbatim}
p(A) =>
    foreach (I in 1 .. A.length)
        E = A[I],
        writeln(E)
    end.
\end{verbatim}
the variables \texttt{I} and \texttt{E} are local\index{local variable}, and each iteration of the loop has its own values for these variables.

\subsection*{Example}
\begin{verbatim}
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.
\end{verbatim}
The function \texttt{read\_list} reads a sequence of integers into a list\index{list}, terminating when 0 is read. The loop corresponds to the following sequence of recurrences:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{$L$=[]} \\
\> \texttt{$L_1$=[$e_1$$|$$L$]} \\
\> \texttt{$L_2$=[$e_2$$|$$L_1$]} \\
\> $\ldots$ \\
\> \texttt{$L_n$=[$e_n$$|$$L_{n-1}$]} \\
\> \texttt{List=$L_n$}
\end{tabbing}
Note that the list\index{list} of integers is in reversed order. If users want a list\index{list} in the same order as the input, then the following loop can be used:
\begin{verbatim}
read_list = List =>
    List = L,
    E = read_int(),
    while (E != 0) 
        L = [E|T],
        L := T,
        E := read_int()
    end,
    L = [].
\end{verbatim}
This loop corresponds to the following sequence of recurrences:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{$L$=[$e_1$$|$$L_1$]} \\
\> \texttt{$L_1$=[$e_2$$|$$L_2$]} \\
\> $\ldots$ \\
\> \texttt{$L_{n-1}$=[$e_n$$|$$L_{n}$]} \\
\> \texttt{$L_n$=[]}
\end{tabbing}
Loop statements are compiled into tail-recursive\index{tail recursion} predicates\index{predicate}. For example, the second \texttt{read\_list} function given above is compiled into:
\begin{verbatim}
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).
\end{verbatim}

A list comprehension\index{list comprehension} is first compiled into a \texttt{foreach} loop\index{foreach loop}, and then the loop is compiled into a call to a generated tail-recursive\index{tail recursion} predicate\index{predicate}. For example, the list comprehension\index{list comprehension} 
\begin{verbatim}
List = [(A,X) : A in [a,b], X in 1..2]
\end{verbatim}
is compiled into the following loop:
\begin{verbatim}
List = L,
foreach (A in [a,b], X in 1..2)
    L = [(A,X)|T],
    L := T
end,
L = [].
\end{verbatim}

\section{Tabling}
A predicate\index{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\index{tabling} can prevent infinite loops and redundancy by memorizing calls and their answers. In order to have all calls and answers of a predicate\index{predicate} or function\index{function} tabled\index{tabling}, users just need to add the keyword \texttt{table}\index{\texttt{table}} before the first rule.

\subsection*{Example}
\begin{verbatim}
table
fib(0) = 1.
fib(1) = 1.
fib(N) = fib(N-1)+fib(N-2).
\end{verbatim}
When not tabled\index{tabling}, the function call \texttt{fib(N)} takes exponential time in \texttt{N}. When tabled\index{tabling}, however, it takes only linear time.

Users can also give table\index{tabling} modes to instruct the system on what answers to table\index{tabling}. Mode-directed tabling\index{mode-directed tabling} is especially useful for dynamic programming problems. In mode-directed tabling\index{mode-directed tabling}, a plus-sign (+) indicates input, a minus-sign (-) indicates output, \texttt{max} indicates that the corresponding variable should be maximized, \texttt{min} indicates that the corresponding variable should be minimized, and \texttt{nt} indicates that the corresponding argument is not tabled.\footnote{An {\tt nt} argument can carry some information that is dependent on the input arguments but useful for the computation.}

\subsection*{Example}
\begin{verbatim}
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.
\end{verbatim}
For a call \texttt{edit(L1,L2,D)}, where \texttt{L1} and \texttt{L2} are given lists\index{list} and \texttt{D} is a variable, the rules can generate all facts, each of which contains a different editing distance between the two lists\index{list}. The table\index{tabling}\index{mode-directed tabling} mode \texttt{table(+,+,min)}\index{\texttt{table}} tells the system to keep a fact with the minimal editing distance. 

A tabled\index{tabling} predicate\index{predicate} can be preceded by both a table\index{tabling} declaration and at most one index declaration\index{index declaration} if it contains facts. The order of these declarations is not important.

\section{Modules}
A module is a source file with the extension \texttt{.pi}. A module begins with a module name declaration and optional import declarations. A module declaration has the form: 
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{module $Name$}\index{\texttt{module}}.
\end{tabbing}
where $Name$ 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\index{global module}, and all of the predicates\index{predicate} and functions\index{function} 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: 
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{import $Name_1$, $\ldots$, $Name_n$}\index{\texttt{import}}.
\end{tabbing}
where each $Name_i$ is a module name. When a module is imported, all of its public predicates\index{predicate} and functions\index{function} will be visible to the importing module. A public predicate\index{predicate} or function\index{function} in a module can also be accessed by preceding it with a module qualifier, as in \texttt{m.p()}, but the module still must be imported.

Atoms\index{atom} and structure\index{structure} names do not belong to any module, and are globally visible. In a module, predicates\index{predicate} and functions\index{function} are assumed to be visible both inside and outside of the module, unless their definitions are preceded by the keyword \texttt{private}. 

\subsection*{Example}
\begin{verbatim}
% 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])).
\end{verbatim}

The predicate \texttt{sum\_aux} is private, and is never visible outside of the module. The following shows a session that uses these modules. 
\begin{verbatim}
Picat> load("test_my_sum")

Picat> go
10
\end{verbatim}
The command \texttt{load(File)}\index{\texttt{load/1}} loads a module file\index{module file} into the system. If the file\index{module file} has not been compiled, then the \texttt{load}\index{\texttt{load/1}} 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.\footnote{Dependent modules must be in a path that is specified by the environment variable PICATPATH.} When a module is loaded, all of its public predicates\index{predicate} and functions\index{function} 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\index{higher-order call}, however, Picat may need to search for their definitions at runtime. Several built-in modules are imported by default, including  \texttt{basic}, \texttt{io}, \texttt{math},  and \texttt{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:
\begin{enumerate}
\item The implicitly imported built-in modules in the order from \texttt{basic}, \texttt{math}, \texttt{io} to \texttt{sys}.
\item The enclosing module of the call.
\item The explicitly imported modules in the order that they were imported.
\item The global module.
\end{enumerate}

\section{\label{section:Constraints}Constraints}
Picat can be used as a modeling and solving language for constraint\index{constraint} satisfaction and optimization problems.  A constraint\index{constraint} program normally poses a problem in three steps: (1) generate variables; (2) generate constraints\index{constraint} over the variables; and (3) call \texttt{solve}\index{\texttt{solve/1}}\index{\texttt{solve/2}} to find a valuation for the variables that satisfies the constraints\index{constraint}, and possibly optimizes an objective function. Picat provides four solver modules, including \texttt{cp}, \texttt{sat}, \texttt{smt}, and \texttt{mip}.

\subsection*{Example}
\begin{verbatim}
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).
\end{verbatim}
In arithmetic constraints\index{constraint}, 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\index{constraint} satisfaction and optimization problems. The following program solves a Sudoku puzzle:
\begin{verbatim}
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}}.
\end{verbatim}
Recall that variables that occur within a loop, and do not occur before the loop in the outer scope\index{scope}, are local\index{local variable} to each iteration of the loop. For example, in the third \texttt{foreach}\index{foreach loop} statement of the \texttt{sudoku} predicate, the variables \texttt{Row}, \texttt{Col}, and \texttt{Square} are local\index{local variable}, and each iteration of the loop has its own values for these variables.

\section{Exceptions}
An exception\index{exception} is an event that occurs during the execution of a program that requires a special treatment. In Picat, an exception\index{exception} is just a term\index{term}. Example exceptions\index{exception} thrown by the system include:
\begin{itemize}
\item \texttt{divide\_by\_zero}
\item \texttt{file\_not\_found}
\item \texttt{number\_expected}
\item \texttt{interrupt}\index{interrupt}
\item \texttt{out\_of\_range}
\end{itemize}
The exception\index{exception} \texttt{interrupt(keyboard)}\index{interrupt} is raised when \texttt{ctrl-c} is typed during a program's execution. The built-in predicate \texttt{throw $Exception$}\index{\texttt{throw/1}} throws $Exception$. 

All exceptions, including those raised by built-ins and interruptions, can be caught by catchers. A catcher is a call in the form: {\tt catch($Goal$,$Exception$,$Handler$)} which is equivalent to $Goal$, except when an exception is raised during the execution of $Goal$ that unifies $Exception$. When such an exception is raised, all of the bindings that have been performed on variables in $Goal$ will be undone, and $Handler$ will be executed to handle the exception. 
\index{\texttt{catch/3}}

The call \texttt{call\_cleanup($Goal$,$Cleanup$)} is equivalent to {\tt call($Call$)}, except that \texttt{$Cleanup$} is called when \texttt{$Goal$} succeeds determinately (i.e., with no remaining choice point), when \texttt{$Goal$} fails, or when \texttt{$Goal$} raises an exception.
\index{\texttt{call\_cleanup/2}}


\section{Higher-Order Calls}
A predicate\index{predicate} or function\index{function} is said to be \emph{higher-order}\index{higher-order call} if it takes calls as arguments. The built-ins \texttt{call}\index{\texttt{call}}, \texttt{apply}\index{\texttt{apply}}, and \texttt{find\_all}\index{\texttt{find\_all/2}} are higher-order\index{higher-order call}. The predicate \texttt{call($S$,$Arg_1$,$\ldots$,$Arg_n$)}\index{\texttt{call}}, where $S$ is an atom\index{atom} or a structure\index{structure}, calls the predicate named by $S$ with the arguments that are specified in $S$ together with extra arguments $Arg_1$,$\ldots$,$Arg_n$. The function \texttt{apply($S$,$Arg_1$,$\ldots$,$Arg_n$)}\index{\texttt{apply}} is similar to \texttt{call}\index{\texttt{call}}, except that \texttt{apply}\index{\texttt{apply}} returns a value. The function \texttt{findall($Template$,$S$)}\index{\texttt{findall/2}} returns a list\index{list} of all possible solutions of \texttt{call($S$)}\index{\texttt{call}} in the form of $Template$. Other higher-order predicates include \verb-\+/1-\index{{\verb-\+/1-}}, \texttt{call\_cleanup/2}\index{\texttt{call\_cleanup/2}}, \texttt{catch/3}\index{\texttt{catch/3}}, \texttt{count\_all}\index{\texttt{count\_all/2}}, \texttt{freeze/2}\index{\texttt{freeze/2}}, \texttt{maxof/2-3}\index{\texttt{maxof/2}}\index{\texttt{maxof/3}}, \texttt{maxof\_inc/2-3}\index{\texttt{maxof\_inc/2}}\index{\texttt{maxof\_inc/3}}, \texttt{minof/2-3}\index{\texttt{minof/2}}\index{\texttt{minof/3}}, \texttt{minof\_inc/2-3}\index{\texttt{minof\_inc/2}}\index{\texttt{minof\_inc/3}}, \texttt{not/1}\index{\texttt{not/1}}, \texttt{once/1}\index{\texttt{once/1}},  \texttt{time/1}\index{\texttt{time/1}}, \texttt{time2/1}\index{\texttt{time/1}}, and \texttt{time\_out/3}\index{\texttt{time\_out/3}}. All of these higher-order predicates are defined in the {\tt basic} module, except for \texttt{time/1}, \texttt{time2/1}, and \texttt{time\_out/3}, which are defined in the {\tt sys} module. Higher-order calls cannot contain assignments or loops.

\subsection*{Example}
\begin{verbatim}
Picat> S = $member(X), call(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
\end{verbatim}
\ignore{
A lambda term\index{term} in the form \texttt{lambda($VList$,$Exp$)}, where $VList$ is a list\index{list} of input variables, and $Exp$ is an expression, denotes an anonymous function\index{function}. The last command in the example is the same as \texttt{Z = apply(add,1,2)}\index{\texttt{apply}}, where \texttt{add} is a function defined as follows:
\begin{verbatim}
add(X,Y) = Z => Z = X+Y.
\end{verbatim}
}

Among the higher-order built-ins, \texttt{findall}\index{\texttt{findall/2}} is special in that it forms a name scope like a loop. Local variables that occur in a \texttt{findall} call are not visible to subsequent calls in the body or query.

The meta-call \texttt{apply}\index{\texttt{apply}} never returns a partially evaluated function\index{function}. If the number of arguments does not match the required number, then it throws an exception\index{exception}.

\subsection*{Example}
\begin{verbatim}
map(_F,[]) = [].
map(F,[X|Xs]) = [apply(F,X)|map(F,Xs)].

map2(_F,[],[]) = [].
map2(F,[X|Xs],[Y|Ys]) = [apply(F,X,Y)|map2(F,Xs,Ys)].

fold(_F,Acc,[]) = Acc.
fold(F,Acc,[H|T]) = fold(F, apply(F,H,Acc),T).
\end{verbatim}

A call that is passed to \texttt{apply} is assumed to invoke a definition in a pre-imported built-in module, the enclosing module in which \texttt{apply} occurs, an imported module of the enclosing module, or the global module. Due to the overhead of runtime search, the use of higher-order calls is discouraged. Whenever possible, recursion, loops, or list and array comprehensions should be used instead.

\section{Action Rules}
Picat provides action rules\index{action rule} for describing event-driven actors\index{action rule}. An actor\index{action rule} is a predicate\index{predicate} call that can be delayed, and can be activated later by events. Each time an actor\index{action rule} is activated, an action can be executed. A predicate\index{predicate} for actors\index{action rule} contains at least one \emph{action rule}\index{action rule} in the form:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> $Head, Cond, \{Event\} $\verb+=>+$\ Body$ 
\end{tabbing}
where $Head$ is an actor\index{action rule} pattern, $Cond$ is an optional condition, $Event$ is a non-empty set of event patterns separated by \texttt{','},  and $Body$ is an action. For an actor\index{action rule} and an event, an action rule\index{action rule} is said to be \emph{applicable} if the actor\index{action rule} matches $Head$ and $Cond$ is true. A predicate\index{predicate} for actors\index{action rule} cannot contain backtrackable rules\index{backtrackable rule}.

An event channel is an attributed variable\index{attributed variable} to which actors\index{action rule} can be attached, and through which events can be posted to actors\index{action rule}. A channel has four ports: \texttt{ins}\index{\texttt{ins}-port}, \texttt{bound}\index{\texttt{bound}-port}, \texttt{dom}\index{\texttt{dom}-port}, and \texttt{any}\index{\texttt{any}-port}. An event pattern in $Event$ specifies the port to which the actor\index{action rule} is attached. The event pattern \texttt{ins($X$)} attaches the actor\index{action rule} to the \texttt{ins}-port\index{\texttt{ins}-port} of channel $X$, and the actor\index{action rule} will be activated when $X$ is instantiated\index{instantiated variable}. The event pattern \texttt{event($X$,$T$)} attaches the actor\index{action rule} to the \texttt{dom}-port\index{\texttt{dom}-port} of channel $X$. The built-in \texttt{post\_event($X$,$T$)}\index{\texttt{post\_event/2}} posts an event term\index{term} \texttt{$T$} to the \texttt{dom}-port\index{\texttt{dom}-port} of channel $X$. After an event is posted to a port of a channel, the actors\index{action rule} attached to that port are activated. For an activated actor\index{action rule}, the system searches for an applicable rule\index{action rule} and executes the rule\index{action rule} body if it finds one. After execution, the actor\index{action rule} is \emph{suspended}, waiting to be activated again by other events. Picat does not provide a built-in for detaching actors\index{action rule} from channels. An actor\index{action rule} \emph{fails} if no rule\index{action rule} is applicable to it when it is activated or the body of the applied rule\index{action rule} fails. An actor\index{action rule} becomes a \emph{normal call} once a normal non-backtrackable rule\index{non-backtrackable rule} is applied to it.

\subsection*{Example}
\begin{verbatim}
echo(X,Flag), var(Flag), {event(X,T)} => writeln(T).
echo(_X,_Flag) => writeln(done).

foo(Flag) => Flag = 1.
\end{verbatim}
When a call \texttt{echo(X,Flag)} is executed, where \texttt{Flag} is a variable, it is attached to the \texttt{dom}-port\index{\texttt{dom}-port} of \texttt{X} as an actor\index{action rule}.  The actor\index{action rule} is then suspended, waiting for events posted to the \texttt{dom}-port\index{\texttt{dom}-port}. For this actor\index{action rule} definition, the command
\begin{small}
\begin{verbatim}
echo(X,Flag), post_event(X,hello), post_event(X,picat).
\end{verbatim}
\end{small}
prints out \texttt{hello} followed by \texttt{picat}. If the call \texttt{foo(Flag)} is inserted before the second call to \texttt{post\_event}, then \texttt{var(Flag)}\index{\texttt{var/1}} fails when the actor\index{action rule} is activated the second time, causing the second rule to be applied to the actor\index{action rule}. Then, the output will be \texttt{hello} followed by \texttt{done}. Note that events are not handled until a non-inline call is executed. Replacing \texttt{foo(Flag)} by \texttt{Flag = 1} will result in a different behavior because \texttt{Flag = 1} is an inline call.

\ignore{
\section{Threads}
A thread\index{thread} is represented as an attributed variable\index{attributed variable} that contains, among other attributes, a thread\index{thread} descriptor. A thread\index{thread} can serve as a communication channel. A thread\index{thread} can send a message to another thread\index{thread} by posting an event. Action rules\index{action rule} can be used to program concurrent threads\index{thread}. 

\subsection*{Example}
\begin{verbatim}
import thread.

go =>
    EchoThread = new_thread(install_echo_actor),  
    SenderThread = new_thread(send,3,EchoThread),
    EchoThread.start(),
    SenderThread.start().

install_echo_actor =>
    echo(this_thread(),Flag),
    loop(Flag).

echo(X,Flag),var(Flag),{event(X,T)} => 
    writeln(T), 
    if (T == done) Flag = 1 end.
echo(_,_) => true.

loop(Flag), var(Flag) => loop(Flag).
loop(_) => true.

send(N,EchoThread) =>
    foreach (I in 1..N)
        post_event(EchoThread,hello)
    end,
    post_event(EchoThread,done).
\end{verbatim}
The built-in function \texttt{new\_thread($S$,$Arg_1$,$\ldots$,$Arg_n$)}\index{\texttt{new\_thread}} creates a new thread\index{thread} to execute the call 
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{call($S$,$Arg_1$,$\ldots$,$Arg_n$)}\index{\texttt{call}}. 
\end{tabbing}
The built-in function \texttt{this\_thread()}\index{\texttt{this\_thread/0}} returns the executing thread\index{thread} of the function call. In this example, the \texttt{EchoThread} installs an actor\index{action rule}, and then loops until \texttt{Flag} becomes a non-variable; the \texttt{SenderThread} sends \texttt{hello} to \texttt{EchoThread} three times, and then sends \texttt{done} to \texttt{EchoThread}, causing it to kill itself. After sending the messages, the \texttt{SenderThread} terminates.
}
\section{\label{prebuiltmaps}Prebuilt Maps}
Picat has three kinds of prebuilt maps: {\it heap} maps, {\it global} maps, and {\it table} maps. Prebuilt heap maps \index{heap map} are created on the heap immediately after the system is started. The built-in function \texttt{get\_heap\_map($ID$)}\index{\texttt{get\_heap\_map/1}} returns the heap map that is associated with $ID$, where $ID$ must be a ground term. If no heap map is associated with $ID$, then this function establishes an association between $ID$ and an unused heap map, and returns the map. A heap map is like a normal map. Users use \texttt{put}\index{\texttt{put/3}} to add key-value pairs into the map\index{map}. Users use \texttt{get}\index{\texttt{get/2}} to retrieve a value that is associated with a key in the map\index{map}. Changes to a heap map up to a choice point are undone when execution backtracks to that choice point. The built-in function \texttt{get\_heap\_map()}\index{\texttt{get\_heap\_map/0}} returns the heap map that is associated with a system-generated default identifier. There are an unlimited number of prebuilt heap maps.

Global maps \index{global map} are created in the global area when the Picat system is started. The built-in function \texttt{get\_global\_map($ID$)}\index{\texttt{get\_global\_map/1}} returns the global map that is associated with $ID$, where $ID$ must be a ground term. If no global map is associated with $ID$, then this function establishes an association between $ID$ 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 \texttt{get\_global\_map()}\index{\texttt{get\_global\_map/0}} 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 \index{table map} are created in the table area when the Picat system is started. The built-in function \texttt{get\_table\_map($ID$)}\index{\texttt{get\_table\_map/1}} returns the table map that is associated with $ID$, where $ID$ must be a ground term. If no table map is associated with $ID$, then this function establishes an association between $ID$ 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 {\it hash-consed} so that common ground sub-terms are not replicated in the table area. The built-in function \texttt{get\_table\_map()}\index{\texttt{get\_table\_map/0}} 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\index{prebuilt map} 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\index{tabling} programs, using prebuilt maps\index{global map} is discouraged because it may cause unanticipated effects.

\subsection*{Example}
\begin{verbatim}
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.
\end{verbatim}
For the call \texttt{go}, the output is:
\begin{verbatim}
heap map h1 has no key
global map g1 has key
table map t1 has key
\end{verbatim}
The \texttt{fail}\index{\texttt{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.

\ignore{
\section{External Language Interfaces and Libraries}
Picat has well-defined interfaces with C and Java. The dynamic libraries (\texttt{dll} or \texttt{so} files) of the Picat system will be made available so that users can easily link Picat programs with external software components though C or Java. Picat also supports access to databases through the ODBC interface.

Picat provides a rich library of modules for applications such as language processing (Regix, DCG, etc.), Web services (server side programming, RIF data processing, semantic web applications, etc.), mobile applications for handheld devices, and game programming. 

\section{Resources}
\begin{itemize}
\item An overview of Picat: \verb+http://www.picat-lang.org/download/picat_proposal.pdf+
\item Examples: \verb+http://www.picat-lang.org/download/exs.pi.txt+
\item Libraries: \verb+http://www.picat-lang.org/download/builtin.pdf+
\item Lexical grammar: \verb+http://www.picat-lang.org/download/lex_grammar.txt+
\item Syntax grammar: \verb+http://www.picat-lang.org/download/syntax_grammar.txt+
\end{itemize}
}
\ignore{
The parser is written in B-Prolog. The zip file \texttt{picat\_win.zip} contains the B-Prolog executable for Windows you need to parse Picat programs. To install the package, do the following:
\begin{enumerate}
\item Download the zip file \verb+picat_win.zip+ and store it in \verb+C:\+.
\item Extract the files by using winzip or jar in JSDK to \verb+C:\+.
\item Add the path \verb+C:\Picat+ to the environment variable \verb+path+, so you can start the parser in any working directory. 
\end{enumerate}
To compile files, use the command
\begin{verbatim}
    picatc file1 file2 ... filen
\end{verbatim}
The file names must be full names with extension names. 

Alternatively, you can parse files using the B-Prolog interpreter. First, start B-Prolog with the command 
\begin{verbatim}
    picat
\end{verbatim}
Note this B-Prolog interpreter differs from the standard one in that it has a special tokenizer for Picat. To compile a file, say \texttt{xxx.pi}, use the Prolog command 
\begin{verbatim}
    parse('xxx.pi')
\end{verbatim}
Note that in B-Prolog (as well as in other Prolog systems), file names are single-quoted.
}

\section{Programming Exercises}
Project Euler (\url{projecteuler.net}) is an excellent platform for practicing programming and problem solving skills. You can find Picat solutions to some of the problems at \url{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.
\ignore{
\end{document}
}
