\documentclass[11pt]{report}
\textwidth 13.7cm
\textheight 21.5cm

\RequirePackage[T1]{fontenc}
\usepackage{chngpage}
\usepackage{makeidx}
\usepackage{multicol}
\usepackage{sectsty}
\usepackage{setspace}
\usepackage{times}
\usepackage{url}
\usepackage{vmargin}

\newcommand{\ignore}[1]{}

\sectionfont{\normalsize\bf}
\subsectionfont{\normalsize\bf}

\newcommand{\myimp}{\verb+ :- +}
\def\definitionname{Definition}

\makeindex

\usepackage[bookmarks=true,hidelinks]{hyperref}
\hypersetup{pdfstartview={XYZ null null 1.00}}

\begin{document}
\vspace*{4cm}
\begin{center}
{\Huge\bf A User's Guide to Picat} \\
{\large\bf Version 3.9 \#3} \\


\vspace*{1cm}
%\vspace*{8cm}

{\large\bf Neng-Fa Zhou and Jonathan Fruhman} \\
\vspace*{1cm}
{\bf Copyright \copyright \url{picat-lang.org}, 2013-2025.} \\
%{\bf Under construction}
{\bf Last updated October 28, 2025} \\
\end{center}
\thispagestyle{empty}
\clearpage

\pagestyle{plain}
\pagenumbering{roman}

\section*{Preface}
Picat is a general-purpose language that incorporates features from logic programming, functional programming, constraint programming,  and scripting languages. The letters in the name summarize Picat's features:

\begin{itemize}
\item \textbf{P}attern-matching: A \emph{predicate} defines a relation, and can have zero, one, or multiple answers. A \emph{function} is a special kind of a predicate that always succeeds with \emph{one} answer. Picat is a rule-based language. Predicates and functions are defined with pattern-matching rules. Since version 3.0, Picat also supports Prolog-style Horn clauses and Definite Clause Grammar (DCG) rules.

\item \textbf{I}ntuitive: Picat provides assignment and loop statements for programming everyday things. An assignable variable mimics multiple logic variables, each of which holds a value at a different stage of computation. Assignments are useful for computing aggregates and are used with the {\tt foreach} loop for implementing list and array comprehensions.

\item \textbf{C}onstraints: Picat supports constraint programming.  Given a set of variables, each of which has a domain of possible values, and a set of constraints that limit the acceptable set of assignments of values to variables, the goal is to find an assignment of values to the variables that satisfies all of the constraints. Picat provides four solver modules: {\tt cp}, {\tt sat}, {\tt smt}, and {\tt mip}. These four modules follow the same interface, which allows for seamless switching from one solver to another.

\item \textbf{A}ctors: Actors are event-driven calls.  Picat provides \emph{action rules} for describing event-driven behaviors of actors. Events are posted through channels. An actor can be attached to a channel in order to watch and to process its events. All the propagators used in {\tt cp} are implemented as actors.
% Picat treats threads as channels, and allows the use of action rules\index{action rule} to program concurrent threads\index{thread}.

\item \textbf{T}abling: Tabling can be used to store the results of certain calculations in memory, allowing the program to do a quick table lookup instead of repeatedly calculating a value. As computer memory grows, tabling is becoming increasingly important for offering dynamic programming solutions for many problems. The \texttt{planner} module, which is implemented by the use of tabling, has been shown to be an efficient tool for solving planning problems.

\end{itemize}

The support of unification, non-determinism, tabling, and constraints makes Picat more suitable than functional and scripting languages for symbolic computations. Picat is more convenient than Prolog for scripting and modeling. With arrays, loops, and comprehensions, it is not rare to find problems for which Picat requires an order of magnitude fewer lines of code to describe than Prolog. Picat is more scalable than Prolog. The use of pattern-matching rather than unification facilitates indexing of rules. Picat is not as powerful as Prolog for metaprogramming and it's impossible to write a meta-interpreter for Picat in Picat itself. Nevertheless, this weakness can be remedied with library modules for implementing domain-specific languages.

The Picat implementation is based on the B-Prolog engine. The current implementation is ready for many kinds of applications. It also serves as a foundation for new additions. The project is open, and you are welcome to join as a developer, a sponsor, a user, or a reviewer. Please contact \url{picat@picat-lang.org} and join the news group \url{https://groups.google.com/g/picat-lang}.



\clearpage
\section*{License}
The copyright of Picat is owned by \url{picat-lang.org}. Picat is provided, free of charge, for any purposes, including commercial ones. The C source files of Picat are covered by the Mozilla Public License, v. 2.0 (\url{http://mozilla.org/MPL/2.0/}). In essence, anyone is allowed to build works, including proprietary ones, based on Picat, as long as the Source Code Form is retained. The copyright holders, developers, and distributors will not be held liable for any direct or indirect damages.

 
\section*{Acknowledgements}
The initial design of Picat was published in December 2012, and the first alpha version was released in May 2013.  Many people have contributed to the project by reviewing the ideas, the design, the implementation, and/or the documentation, including Roman Bart\'{a}k, Nikhil Barthwal, Mike Bionchik, Lei Chen, Veronica Dahl, Claudio Cesar de S\'{a}, Agostino Dovier, Sergii Dymchenko, Julio Di Egidio, Christian Theil Have, H{\aa}kan Kjellerstrand,  Annie Liu, Nuno Lopes, Marcio Minicz, Richard O'Keefe, Lorenz Schiffmann, Paul Tarau, and Jan Wielemaker.  Special thanks to H{\aa}kan Kjellerstrand, who has been programming in Picat and blogging about Picat since May 2013. The system wouldn't have matured so quickly without H{\aa}kan's hundreds of programs (\url{http://hakank.org/}). Thanks also go to Bo Yuan (Bobby) Zhou, who designed the \url{picat-lang.org} web page, Sanders Hernandez, who implemented the interface to the FANN neural network library, and Domingo Alvarez Duarte, who ported Picat to MinGW (\url{https://github.com/mingodad/picat}). The Picat project was supported in part by the NSF under grant numbers CCF1018006 and CCF1618046.

The Picat implementation is based on the B-Prolog engine. It uses the following public domain modules: \ignore{\texttt{prism} by Taisuke Sato and Yoshitaka Kameya; }\texttt{token.c} by Richard O'Keefe; \texttt{getline.c} by Chris Thewalt; \texttt{bigint.c} by Matt McCutchen; \texttt{Espresso} (by Berkeley); \texttt{FANN} by Steffen Nissen. In addition, Picat also provides interfaces to the SAT solver Kissat (\url{https://github.com/arminbiere/kissat}), \texttt{Gurobi} by Gurobi Optimization, Inc, \texttt{CBC} by John Forrest, \texttt{GLPK} by Andrew Makhorin, \texttt{SCIP} by the Zuse Institute, and \texttt{Z3} by Microsoft.

\tableofcontents

\cleardoublepage
\pagestyle{plain}
\setcounter{page}{1}
\pagenumbering{arabic}

\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}
}
\ignore{
\documentstyle[11pt]{report}
\textwidth 13.7cm
\textheight 21.5cm
\newcommand{\myimp}{\verb+ :- +}
\newcommand{\ignore}[1]{}
\def\definitionname{Definition}

\makeindex
\begin{document}
}
\chapter{How to Use the Picat System}
\section{How to Use the Picat Interpreter}
The Picat system is written in both C and Picat. The Picat interpreter is provided as a single standalone executable file, named \texttt{picat.exe} for Windows and \texttt{picat} for Unix. The Picat interpreter provides an interactive programming environment for users to compile, load, debug, and execute programs. In order to start the Picat interpreter, users first need to open an OS terminal. In Windows, this can be done by selecting \verb+Start -> Run+ and typing \verb+cmd+ or selecting \verb+Start -> Programs -> Accessories -> Command Prompt+.  In order to start the Picat interpreter in any working directory, the environment variable \texttt{path} must be properly set to contain the directory where the executable is located.

\subsection{How to Enter and Quit the Picat Interpreter}
The Picat interpreter is started with the OS command \texttt{picat}\index{\texttt{picat}}. 
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> $OSPrompt$ \texttt{picat}
\end{tabbing}
where $OSPrompt$ is the OS prompt. After the interpreter is started, it responds with the prompt \verb+Picat>+, and is ready to accept queries. 

In general, the \texttt{picat} command takes the following form:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{picat $Opts$ $PicatMainFileName$ $A_1$ $A_2$ $\ldots$ $A_n$}
\end{tabbing}
where $PicatMainFileName$ can have the extension \texttt{.pi} and can contain a path of directories, and $Opts$ is a sequence of options of the following:
\begin{itemize}
\item \texttt{-d}: This option puts Picat in debug mode after Picat is started. In debug mode, execution can be traced, and the stack trace is printed once an error occurs.

\item \texttt{-g $InitGoal$}: This option makes Picat execute a specified initial query $InitGoal$ rather than the default \texttt{main} predicate.

\item \texttt{--help}: Print out the help info.

\item \texttt{-log}: The option \texttt{-log} makes the system print log information and warning messages. 

\item \texttt{-path $Directories$}: $Directories$ is a semicolon-separated and double-quoted list of directories. This option sets the value of the environment variable \texttt{PICATPATH} before the execution of the program. The Picat system will look for $PicatMainFileName$ and the related modules in these directories. 

\item \texttt{-s $Size$}: This option reserves $Size$ words for the stack and the heap when the system is started.

\item \texttt{--v}:
\item \texttt{--version}: This option makes Picat print the version number.
\end{itemize}

Once the interpreter is started, users can type a query after the prompt. For example,
\begin{verbatim}
      Picat> X = 1+1
      X = 2
      Picat> printf("hello"++" picat")
      hello picat
\end{verbatim}
\ignore{
Users can change the prompt by using the query \texttt{prompt($NewPrompt$)}\index{\texttt{prompt/1}}. For example, the command
\begin{verbatim}
      prompt("?-")
\end{verbatim}
changes the prompt to \verb+?-+. The \texttt{help}\index{\texttt{help/0}} predicate shows the usages of the main commands.
}

The \texttt{halt}\index{\texttt{halt/0}} predicate, or the \texttt{exit}\index{\texttt{exit/0}} predicate, terminates the Picat interpreter. An alternative way to terminate the interpreter is to enter \verb+ctrl-d+ (control-d) when the cursor is located at the beginning of an empty line.

\ignore{
\subsection{How to Run a Program Directly}
The \texttt{picat} command can also be used to run a program directly. Consider the following program:
\begin{verbatim}
    main =>
        printf("hello picat%n").

    main(Args) =>
        printf("hello picat"),
        foreach (Arg in Args)
            printf(" %s",Arg)
        end,
        nl.
\end{verbatim}
Assume the program is stored in a file named \texttt{hello.pi} in the directory \verb+C:\work+. The following shows two runs, one executing \texttt{main/0} and the other executing \texttt{main/1}.
\begin{verbatim}
    C:\work> picat hello.pi
    hello picat

    C:\work> picat hello.pi 6 12 2013
    hello picat 6 12 2013
\end{verbatim}
If the command line contains arguments after the file name, then \texttt{main/1} is executed and all the arguments are passed to the predicate as a list of strings.

In general, the \texttt{picat} command takes the following form:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> \texttt{picat [-path $Directories$][-log] [-g $InitGoal$] $File$ $Arg_1$ $Arg_2$ $\ldots$ $Arg_n$}
\end{tabbing}
$Directories$ is a semicolon-separated and double-quoted list of directories, and will be set as the value of the environment variable \texttt{PICATPATH} before the execution of the program. The Picat system will look for the file and the related modules in these directories. The option \texttt{-log} makes the system print log information and warning messages. The option \texttt{-g} makes Picat execute a specified initial query $InitGoal$ rather than the default \texttt{main} predicate. The file name $File$ can have the extension \texttt{.pi}, and can contain a path of directories.
}
\subsection{How to Use the Command-line Editor}
The Picat interpreter uses the \texttt{getline} program written by Chris Thewalt. The \texttt{getline} program memorizes up to 100 of the most recent queries that the users have typed, and allows users to recall past queries and edit the current query by using Emacs editing commands. The following gives the editing commands:

\begin{tabular}{ll}
\verb+ctrl-f+ & Move the cursor one position forward. \\
\verb+ctrl-b+ & Move the cursor one position backward. \\
\verb+ctrl-a+ & Move the cursor to the beginning of the line. \\
\verb+ctrl-e+ & Move the cursor to the end of the line.  \\
\verb+ctrl-d+ & Delete the character under the cursor.  \\
\verb+ctrl-h+ & Delete the character to the left of the cursor.  \\
\verb+ctrl-k+ & Delete the characters to the right of the cursor. \\
\verb+ctrl-u+ & Delete the whole line.  \\
\verb+ctrl-p+ & Load the previous query in the buffer.  \\
\verb+ctrl-n+ & Load the next query in the buffer.
\end{tabular}

\noindent
Note that the command \verb+ctrl-d+ terminates the interpreter if the line is empty and the cursor is located in the beginning of the line.

\subsection{How to Compile and Load Programs}
A Picat program is stored in one or more text files with the extension name \texttt{pi}. A file name\index{file name} is a string of characters. Picat treats both  \verb+'/'+ and \verb+'\'+ as file name\index{file name} separators. Nevertheless, since \verb+'\'+ is used as the escape character in quoted strings, two consecutive backslashes must be used, as in \verb+"c:\\work\\myfile.pi"+, if \verb+'\'+ is used as the separator.

A program file can contain \texttt{include} directives of the form:\index{\texttt{include} directive}
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{include $Name$}.
\end{tabbing}
The \texttt{include} directive causes the content of the file named $Name$ to be copied verbatim to where the directive occurs. 

For the sake of demonstration we assume the existence of a file named \texttt{welcome.pi} in the current working directory that stores the following program:
\begin{verbatim}
    main =>
        print(" Welcome to PICAT's world! \n ").

    main(Args) =>
        print(" Welcome to PICAT's world! \n"),
        foreach (Arg in Args)
            printf("%s\n", Arg)
        end.
\end{verbatim}

\begin{itemize}
\item \texttt{cl($FileName$)}: A program first needs to be compiled and loaded into the system before it can be executed. The built-in predicate \texttt{cl($FileName$)}\index{\texttt{cl/1}} compiles and loads the source file named \texttt{$FileName$.pi}. Note that if the full path of the file name\index{file name} is not given, then the file is assumed to be in the current working directory. Also note that users do not need to give the extension name. The system compiles and loads not only the source file \texttt{$FileName$.pi}, but also all of the module files\index{module file} that are either directly imported or indirectly imported by the source file. The system searches for such dependent files in the directory in which \texttt{$FileName$.pi} resides or the directories that are stored in the environment variable\index{environment variable} \texttt{PICATPATH}. For \texttt{$FileName$.pi}, the \texttt{cl} command loads the generated byte-codes without creating a byte-code file. For example,
\begin{verbatim}
Picat> cl("welcome")
Compiling:: welcome.pi
welcome.pi compiled in 4 milliseconds
\end{verbatim}

\item \texttt{cl}: The built-in predicate \texttt{cl}\index{\texttt{cl/0}} (with no argument) compiles and loads a program from the console, ending when the end-of-file character ({\tt ctrl-z} for Windows and {\tt ctrl-d} for Unix) is typed.

\item \texttt{compile($FileName$)}: The built-in predicate \texttt{compile($FileName$)}\index{\texttt{compile/1}} compiles the file \texttt{$FileName$.pi} and all of its dependent module files\index{module file} without loading the generated byte-code files. The destination directory for the byte-code file is the same as the source file's directory. If the Picat interpreter does not have permission to write into the directory in which a source file resides, then this built-in throws an exception. For example,

\begin{verbatim}
Picat> compile("welcome")
Compiling::welcome.pi
welcome.pi compiled in 4 milliseconds
\end{verbatim}

\item \texttt{load($FileName$)}: The built-in predicate \texttt{load($FileName$)}\index{\texttt{load/1}} loads the byte-code file \texttt{$FileName$.qi} and all of its dependent byte-code files. For $FileName$ and its dependent file names\index{file name},  the system searches for a byte-code file in the directory in which \texttt{$FileName$.qi} resides or the directories that are stored in the environment variable\index{environment variable} \texttt{PICATPATH}. If the byte-code file \texttt{$FileName$.qi} does not exist but the source file \texttt{$FileName$.pi} exists, then this built-in compiles the source file and loads the byte codes without creating a {\tt qi} file.

\begin{verbatim}
Picat> load("welcome")
loading...welcome.qi
\end{verbatim}
\end{itemize}

\subsection{How to Run Programs}
After a program is loaded, users can query the program. For each query, the system executes the program, and reports \texttt{yes} when the query succeeds and \texttt{no} when the query fails. When a query that contains variables succeeds, the system also reports the bindings for the variables. For example,

\begin{verbatim}
Picat> cl("welcome")
Compiling:: welcome.pi
welcome.pi compiled in 4 milliseconds
loading...

yes

Picat> main
 Welcome to PICAT's world! 
 
yes
\end{verbatim}

Users can ask the system to find the next solution by typing \texttt{';'} after a solution if the query has multiple solutions. For example,
\begin{verbatim}
    Picat> member(X,[1,2,3])
    X = 1;
    X = 2;
    X = 3;
    no
\end{verbatim}
Users can force a program to terminate by typing \texttt{ctrl-c}, or by letting it execute the built-in predicate \texttt{abort}\index{\texttt{abort/0}}. Note that when the system is engaged in certain tasks, such as garbage collection, users may need to wait for a while in order to see the termination after they type \texttt{ctrl-c}.

\subsection{How to Run Programs Directly}
Programs that define the \texttt{main/0} predicate or the \texttt{main/1} predicate can be run directly as a OS command. For example,
\begin{verbatim}
$ picat welcome
 Welcome to PICAT's world!

$ picat welcome a b c
 Welcome to PICAT's world!
a
b
c
\end{verbatim}
The\/ '{\texttt \$}' sign is the prompt of the OS. It is assumed that the environment variable \texttt{PATH} has been set to contain the directory of the executable \texttt{picat} (\texttt{picat.exe} for Windows), and the environment variable \texttt{PICATPATH} has been set to contain the directory of the \texttt{welcome.pi} file or the file is in the current working directory.

\subsection{Creating Standalone Executables}
It is possible to create a script that can be run as a standalone executable.\index{standalone} For example, consider the following script \texttt{welcome.exe} for Linux:

\begin{verbatim}
#!/bin/bash          
picat welcome.pi
echo " Finished!"
\end{verbatim}
Once the environment variables \texttt{PATH} and \texttt{PICATPATH} are set properly, and the script is set to have the execution permission, it can be executed as follows:

\begin{verbatim}
$ welcome.exe 
 Welcome to PICAT's world! 
 Finished!
\end{verbatim}

\section{How to Use the Debugger}
The Picat system has three execution modes: \textit{non-trace mode}\index{non-trace mode}, \textit{trace mode}\index{trace mode}, and \textit{spy mode}\index{spy mode}.  In trace mode\index{trace mode}, it is possible to trace the execution of a program, showing every call in every possible stage.  In order to trace the execution, the program must be recompiled while the system is in trace mode\index{trace mode}.  In spy mode\index{spy mode}, it is possible to trace the execution of individual functions and predicates that are {\it spy points}. When the Picat interpreter is started, it runs in non-trace mode\index{non-trace mode}. The predicate \texttt{debug}\index{\texttt{debug/0}} or \texttt{trace}\index{\texttt{trace/0}}  changes the mode to trace\index{trace mode}. The predicate \texttt{nodebug}\index{\texttt{nodebug/0}} or \texttt{notrace}\index{\texttt{notrace/0}} changes the mode to non-trace\index{non-trace mode}.

In trace mode\index{trace mode}, the debugger displays execution traces\index{execution trace} of queries. An \emph{execution trace}\index{execution trace} consists of a sequence of call traces\index{call trace}. Each \emph{call trace}\index{call trace} is a line that consists of a stage, the number of the call, and the information about the call itself. For a function call, there are two possible stages: \texttt{Call}, meaning the time at which the function is entered, and \texttt{Exit},  meaning the time at which the call is completed with an answer. For a predicate call, there are two additional possible stages: \texttt{Redo}, meaning a time at which execution backtracks to the call, and \texttt{Fail}, meaning the time at which the call is completed with a failure. The information about a call includes the name of the call, and the arguments. If the call is a function, then the call is followed by \texttt{=} and \texttt{?} at the \texttt{Call} stage, and followed by \texttt{= $Value$} at the \texttt{Exit} stage, where $Value$ is the return value of the call. 

Consider, for example, the following program:
\begin{verbatim}
    p(X) ?=> X = a.
    p(X) => X = b.
    q(X) ?=> X = 1.
    q(X) => X = 2.
\end{verbatim}
Assume the program is stored in a file named \texttt{myprog.pi}. The following shows a trace for a query:
\begin{verbatim}
 Picat> debug

 {Trace mode}
 Picat> cl(myprog)

 {Trace mode}
 Picat> p(X), q(Y)  
    Call: (1) p(_328) ?
    Exit: (1) p(a) 
    Call: (2) q(_378) ?
    Exit: (2) q(1) 
 X = a
 Y = 1 ?;
    Redo: (2) q(1) ?
    Exit: (2) q(2) 
 X = a
 Y = 2 ?;
    Redo: (1) p(a) ?
    Exit: (1) p(b) 
    Call: (3) q(_378) ?
    Exit: (3) q(1) 
 X = b
 Y = 1 ?;
    Redo: (3) q(1) ?
    Exit: (3) q(2) 
 X = b
 Y = 2 ?;
 no
\end{verbatim}

In trace mode\index{trace mode}, the debugger displays every call in every possible stage. Users can set \emph{spy points}\index{spy point} so that the debugger only shows information about calls of the symbols that users are spying. Users can use the predicate 
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{spy \$$Name$/$N$}\index{\texttt{spy/1}} 
\end{tabbing}
to set the functor $Name$/$N$ as a spy point\index{spy point}, where the arity $N$ is optional. If the functor is defined in multiple loaded modules, then all these definitions will be treated as spy points\index{spy point}. If no arity is given, then any functor of $Name$ is treated as a spy point\index{spy point}, regardless of the arity.

After displaying a call trace\index{call trace}, if the trace is for stage \texttt{Call} or stage \texttt{Redo}, then the debugger waits for a command from the users. A command is either a single letter followed by a carriage-return, or just a carriage-return. See Appendix \ref{chapter:sys} for the debugging commands.


\ignore{
\section{How to Use the \texttt{picate} and \texttt{picatc} Commands}
The script file \texttt{picate}\index{\texttt{picate}} executes a Picat program as a standalone application. The command is used in the following way:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{picate -path $Path_1$;$\ldots$;$Path_n$  -debug $FileName$ $Arg_1$ $\ldots$ $Arg_m$ }\index{\texttt{picate}}
\end{tabbing}
where the option \texttt{path} specifies the paths where byte code files are searched, and the option \texttt{debug} tells the system to load \texttt{dbpi} byte code files rather than optimized \texttt{pi} files. Although users cannot use the debugger when running a standalone application in debug mode\index{debug mode}, users can view the stack trace in case an uncaught exception occurs during the execution. The command takes exactly one file name\index{file name} $FileName$. The $FileName$'s byte code file and all of its dependent byte code files will be loaded. The system will search for the byte code files in the paths that are specified in the command. If no path is given, then the system searches the paths that are included in the environment variable\index{environment variable} \texttt{\$PICATPATH}. The command can also take several arguments after the file name\index{file name}. The file of $FileName$ must contain a predicate named \texttt{main($Args$)}, where $Args$ is a list. All of the command arguments $Arg_1$ $\ldots$ $Arg_m$ will be passed to the \texttt{main} predicate as a list of strings.

The script file \texttt{picatc}\index{\texttt{picatc}} compiles Picat source files. The command is used in the following way:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{picatc -path $Path_1$;$\ldots$;$Path_n$ -debug $FileName_1$ $\ldots$ $FileName_n$}\index{\texttt{picatc}}
\end{tabbing}
where the options are the same as in the command \texttt{picate}\index{\texttt{picatc}}. The command compiles all of the source files $FileName_1$ $\ldots$ $FileName_n$ and all of their dependent files into byte code files. If the option \texttt{debug} is given, then the debuggable byte code files with the extension name \texttt{dbqi} are generated; otherwise, the optimized byte code files with the extension name \texttt{qi} are generated.

\section{How to Use the Profiler}
The built-in predicate \texttt{profile\_src($FileName$)}\index{\texttt{profile\_src/1}}, where $FileNames$ is the main name of a source file, reports the following information about the source file and all of its dependent files:
\begin{itemize}
\item What predicates and functions are defined?
\item What predicates and functions are used but not defined?
\item What predicates and functions are  defined but not used?
\item What built-ins are used?
\end{itemize}
The predicate \texttt{profile\_src}\index{\texttt{profile\_src/1}} can be used in both debug\index{debug mode} and non-debug\index{non-debug mode} modes.

The built-in predicate \texttt{profile($Query$)}\index{\texttt{profile/1}} prints the number of times that each predicate or function is called during the execution of $Query$.  The reported statistics are helpful for fine-tunning programs for better performance. The  predicate \texttt{profile}\index{\texttt{profile/1}} can be used only in debug mode\index{debug mode} with \texttt{dbpi} files.
}
\ignore{
\end{document}
}
\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:datatypes}Data Types, Operators, and Built-ins}
Picat is a dynamically-typed language, in which type checking occurs at runtime. A variable gets a type once it is bound to a value. In Picat, variables and values are terms. A value can be \emph{primitive}\index{primitive value} or \emph{compound}\index{compound value}. A primitive value\index{primitive value} can be an \emph{integer}\index{integer}, a \emph{real number}\index{number}, or an \emph{atom}\index{atom}. A compound value\index{compound value} can be a \emph{list}\index{list} or a \emph{structure}\index{structure}. \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}. This chapter describes the data types and the built-ins for each data type that are provided by the \texttt{basic} module. 

Many of the built-ins are given as operators. Table \ref{tab:ops} shows all of the operators that are provided by Picat. Unless the table specifies otherwise, the operators are left-associative.  The as-pattern operator (\verb+@+) and the operators for composing goals, including \texttt{not}\index{\texttt{not/1}}, \texttt{once}\index{\texttt{once/1}}, conjunction (\verb+,+ and \verb+&&+), and disjunction (\verb+;+ and \verb+||+), will be described in Chapter \ref{chapter:predicates} on Predicates and Functions.  The constraint operators (the ones that begin with \verb+#+) will be described in Chapter \ref{ch:constraints} on Constraints. In Picat, no new operators can be defined, and none of the existing operators can be redefined.

The dot operator (\verb+.+) is used in OOP notations for calling predicates and functions. It is also used to qualify calls with a module name. 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$.  If an atom\index{atom} needs to be passed as the first argument to a function or a predicate, then this notation cannot be used. The notation $A.Attr$, where $Attr$ does not have the form \texttt{f($\ldots$)}, is the same as the function call \texttt{get$(A,Attr)$}\index{\texttt{get/2}}. For example, the expression \texttt{$S$.name}\index{\texttt{name/1}} returns the name, and the expression \texttt{$S$.arity}\index{\texttt{arity/1}} returns the arity\index{arity} of $S$ if $S$ is a structure\index{structure}.   Note that the dot operator is left-associative.  For example, the expression \texttt{X.f().g()} is the same as \texttt{g(f(X))}. Also note that functions in dot notation are always evaluated eagerly, and therefore should not be used in term constructs or constraint expressions.

\begin{table}
\caption{\label{tab:ops}Operators in Picat}
\begin{center}
\begin{tabular}{ |c|c| } \hline
Precedence & Operators  \\ \hline \hline
Highest    & \verb+.+, \verb+@+ \\ \hline
           & \verb+**+ (right-associative) \\ \hline
           & unary \verb-+-, unary \verb+-+, \verb+~+  \\ \hline 
           & \verb+*+, \verb+/+, \verb+//+, \verb+/<+, \verb+/>+, \verb+div+, \verb+mod+, \verb+rem+ \\ \hline 
           & binary \verb-+-, binary \verb+-+ \\ \hline 
           & \verb+>>+, \verb+<<+ \\ \hline 
           & \verb+/\+ \\ \hline 
           & \verb+^+ \\ \hline 
           & \verb+\/+ \\ \hline 
           & \verb+..+ \\ \hline 
           & \verb-++- (right-associative) \\ \hline 
           & \verb+=+, \verb+!=+,  \verb+:=+,  \verb+==+, \verb+!==+, \verb+=:=+, \verb+<+,  \verb+=<+, \verb+<=+, \verb+>+,  \verb+>=+, \verb+::+, \verb+in+, \verb+notin+, \verb+=..+  \\ 
           &  \verb+#=+,  \verb+#!=+, \verb+#<+,  \verb+#=<+, \verb+#<=+, \verb+#>+, \verb+#>=+, \verb+@<+, \verb+@=<+, \verb+@<=+, \verb+@>+, \verb+@>=+  \\ \hline 
           & \verb+#~+ \\ \hline 
           & \verb+#/\+ \\ \hline 
           & \verb+#^+ \\ \hline 
           & \verb+#\/+ \\ \hline 
           & \verb+#=>+ (right-associative)\\ \hline 
           & \verb+#<=>+ \\ \hline 
           & \verb+not+, \verb+once+, \verb-\+-  \\ \hline 
           & \verb+,+ (right-associative), $\&\&$ (right-associative) \\ \hline 
Lowest     & \verb+;+ (right-associative), $|$$|$ (right-associative) \\ \hline
\end{tabular}
\end{center}

\end{table}

The following functions are provided for all terms:
\begin{itemize}
\item \texttt{copy\_term($Term_1$) = $Term_2$}\index{\texttt{copy\_term/1}}: This function copies $Term_1$ into $Term_2$.  If $Term_1$ is an attributed variable\index{attributed variable}, then $Term_2$ will not contain any of the attributes.
\item \texttt{copy\_term\_shallow($Term_1$) = $Term_2$}\index{\texttt{copy\_term\_shallow/1}}: This function copies the skeleton of $Term_1$ into $Term_2$. If $Term_1$ is a variable or an atomic value, then it returns a complete copy of $Term_1$, the same as \texttt{copy\_term($Term_1$)}; if $Term_1$ is a list, then it returns a cons \texttt{[$H$$|$$T$]} where both the car $H$ and the cdr $T$ are free variables; otherwise, it is the same as \texttt{new\_struct(name($Term_1$),arity($Term_1$))}.
\item \texttt{hash\_code($Term$) = $Code$}\index{\texttt{hash\_code/1}}: This function returns the hash code of $Term$. If $Term$ is a variable, then the returned hash code is always 0.
\item \texttt{to\_codes($Term$) = $Codes$}\index{\texttt{to\_codes/1}}: This function returns a list of character codes of $Term$.
\item \texttt{to\_fstring($Format$,$Args\ldots$)}\index{\texttt{to\_fstring}}: This function converts the arguments in the $Args\ldots$ parameter into a string, according to the format string $Format$, and returns the string. The number of arguments in $Args\ldots$ cannot exceed 10. Format characters are described in Chapter \ref{chapter:io}.
\item \texttt{to\_string($Term$) = $String$}\index{\texttt{to\_string/1}}: This function returns a string representation of $Term$.
\end{itemize}
Other built-ins on terms are given in Sections \ref{sec:unification} and \ref{sec:otherbuiltins}.

\section{Variables}
Variables in Picat, like variables in mathematics, are value holders. Unlike variables in imperative languages, Picat variables are not symbolic addresses of memory locations. A variable is said to be \emph{free}\index{free variable} if it does not hold any value. A variable is \emph{instantiated}\index{instantiated variable} when it is bound to a value. Picat variables are \emph{single-assignment}\index{single-assignment}, which means that after a variable is instantiated\index{instantiated variable} to a value, the variable will have the same identity as the value. After execution backtracks over a point where a binding took place, the value that was assigned to a variable will be dropped, and the variable will be turned back into a free variable\index{free variable}.

A variable name is an identifier that begins with a capital letter or the underscore. For example, the following are valid variable names:
\begin{verbatim}
    X1   _   _ab
\end{verbatim}
The name \verb+_+ is used for \emph{anonymous variables}\index{anonymous variable}. In a program, different occurrences of \verb+_+ are treated as different variables. So the test \verb+ _ == _+ is always false.

The following two built-ins are provided to test whether a term is a free variable\index{free variable}:
\begin{itemize}
\item \texttt{var($Term$)}\index{\texttt{var/1}}: This predicate is true if $Term$ is a free variable\index{free variable}.
\item \texttt{nonvar($Term$)}\index{\texttt{nonvar/1}}: This predicate is true if $Term$ is not a free variable\index{free variable}.
\end{itemize}

An \emph{attributed variable}\index{attributed variable} is a variable that has a map\index{map} of attribute-value pairs attached to it. The following built-ins are provided for attributed variables\index{attributed variable}:

\begin{itemize}
\item \texttt{attr\_var($Term$)}\index{\texttt{attr\_var/1}}: This predicate is true if $Term$ is an attributed variable\index{attributed variable}.
\item \texttt{dvar($Term$)}\index{\texttt{dvar/1}}: This predicate is true if $Term$ is an attributed domain variable.
\item \texttt{bool\_dvar($Term$)}\index{\texttt{bool\_dvar/1}}: This predicate is true if $Term$ is an attributed domain variable whose lower bound is 0 and whose upper bound is 1.
\item \texttt{dvar\_or\_int($Term$)}\index{\texttt{dvar\_or\_int/1}}: This predicate is true if $Term$ is an attributed domain variable or an integer.
\item \texttt{get\_attr($X$,$Key$) = $Val$}\index{\texttt{get\_attr/2}}: This function returns the \texttt{$Val$} of the key-value pair \texttt{$Key$$=$$Val$} that is attached to \texttt{$X$}. It throws an error if \texttt{$X$} has no attribute named $Key$.
\item \texttt{get\_attr($X$,$Key$,$DefaultVal$) = $Val$}\index{\texttt{get\_attr/3}}: This function returns \texttt{$Val$} of the key-value pair \texttt{$Key$$=$$Val$} that is attached to \texttt{$X$}. It returns $DefaultVal$ if $X$ does not have the attribute named $Key$.
\item \texttt{put\_attr($X$,$Key$,$Val$)}\index{\texttt{put\_attr/3}}: This predicate attaches the key-value pair \texttt{$Key$$=$$Val$} to \texttt{$X$}, where \texttt{$Key$} is a non-variable term, and \texttt{$Val$} is any term. 
\item \texttt{put\_attr($X$,$Key$)}\index{\texttt{put/2}}: The same as \texttt{put\_attr($X$,$Key$,not\_a\_value)}.
\end{itemize}

\section{Atoms}
An atom\index{atom} is a symbolic constant. An atom\index{atom} name can either be quoted or unquoted. An unquoted name is an identifier that begins with a lower-case letter, followed by an optional string\index{string} of letters, digits, and underscores. A quoted name is a single-quoted sequence of arbitrary characters. A character can be represented as a single-character atom\index{atom}. For example, the following are valid atom\index{atom} names:
\begin{verbatim}
    x   x_1   '_'   '\\'   'a\'b\n'   '_ab'   '$%'
\end{verbatim}
No atom\index{atom} name can last more than one line.   An atom\index{atom} name cannot contain more than 1000 characters. The backslash character \verb+'\'+ is used as the escape character. So, the name \verb+'a\'b\n'+ contains four characters: \texttt{a}, \texttt{'}, \texttt{b}, and \verb+\n+.

The following built-ins are provided for atoms\index{atom}:
\begin{itemize}
\item \texttt{ascii\_alpha($Term$)}\index{\texttt{ascii\_alpha/1}}: This predicate is true if $Term$ is an atom and the atom is made of one letter.
\item \texttt{ascii\_alpha\_digit($Term$)}\index{\texttt{ascii\_alpha\_digit/1}}: This predicate is true if $Term$ is an atom and the atom is made of one letter or one digit.
\item \texttt{ascii\_digit($Term$)}\index{\texttt{ascii\_digit/1}}: This predicate is true if $Term$ is an atom and the atom is made of one digit.
\item \texttt{ascii\_lowercase($Term$)}\index{\texttt{ascii\_lowercase/1}}: This predicate is true if $Term$ is an atom and the atom is made of one lowercase letter.
\item \texttt{ascii\_uppercase($Term$)}\index{\texttt{ascii\_uppercase/1}}: This predicate is true if $Term$ is an atom and the atom is made of one uppercase letter.
\item \texttt{atom($Term$)}\index{\texttt{atom/1}}: This predicate is true if $Term$ is an atom\index{atom}.
\item \texttt{atom\_chars($Atm$) = $String$}\index{\texttt{atom\_chars/1}}: This function returns string\index{string} that contains the characters of the atom\index{atom} $Atm$. It throws an error if $Atm$ is not an atom\index{atom}.
\item \texttt{atom\_codes($Atm$) = $List$}\index{\texttt{atom\_codes/1}}: This function returns the list\index{list} of codes of the characters of the atom\index{atom} $Atm$. It throws an error if $Atm$ is not an atom\index{atom}. 
\item \texttt{atomic($Term$)}\index{\texttt{atomic/1}}: This predicate is true if $Term$ is an atom\index{atom} or a number\index{number}.
\item \texttt{char($Term$)}\index{\texttt{char/1}}: This predicate is true if $Term$ is an atom and the atom is made of one character.
\item \texttt{chr($Code$) = $Char$}\index{\texttt{chr/1}}: This function returns the UTF-8 character of the code point $Code$.  
\item \texttt{digit($Term$)}\index{\texttt{digit/1}}: This predicate is true if $Term$ is an atom and the atom is made of one digit.
\item \texttt{len($Atom$) = $Len$}\index{\texttt{len/1}}: This function returns the number of characters in $Atom$. Note that this function is overloaded in such a way that the argument can also be an array, a list, or a structure.
\item \texttt{length($Atom$) = $Len$}\index{\texttt{length/1}}: This function is the same as \texttt{len($Atom$)}.
\item \texttt{ord($Char$) = $Int$}\index{\texttt{ord/1}}: This function returns the code point of the UTF-8 character $Char$.  It throws an error if $Char$ is not a single-character atom.
\end{itemize}

\section{Numbers}
A number\index{number} can be an integer\index{integer} or a real number\index{number}. An integer\index{integer} can be a decimal numeral, a binary numeral, an octal numeral, or a hexadecimal numeral. In a numeral, digits can be separated by underscores, but underscore separators are ignored by the tokenizer. For example, the following are valid integers\index{integer}:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{12\_345} \> \> \> a decimal numeral \\
\> \texttt{0b100} \> \> \> 4 in binary notation  \\
\> \texttt{0o73} \> \> \>  59 in octal notation \\
\> \texttt{0xf7} \> \> \>  247 in hexadecimal notation  
\end{tabbing}

A real number\index{number} consists of an optional integer part\index{integer}, an optional decimal fraction preceded by a decimal point, and an optional exponent. If an integer part\index{integer} exists, then it must be followed by either a fraction or an exponent in order to distinguish the real number\index{number} from an integer literal\index{integer}. For example, the following are valid real numbers\index{number}.
\begin{verbatim}
    12.345   0.123   12-e10   0.12E10
\end{verbatim}

Table \ref{tab:arithdef} gives the meaning of each of the numeric operators in Picat, from the operator with the highest precedence (\verb+**+) to the one with the lowest precedence (\verb+..+). Except for the power operator \verb+**+, which is right-associative, all of the arithmetic operators are left-associative. 

\begin{table}
\caption{\label{tab:arithdef}Arithmetic Operators}
\begin{center}
\begin{tabular}{ |c|c| } \hline
 \texttt{$X$ ** $Y$}  &  power \\ \hline 
 \texttt{+$X$}      &  same as $X$ \\ \hline
 \texttt{-$X$}      &  sign reversal \\ \hline 
 {\tt \verb+~+$X$ }  &   bitwise complement \\ \hline 
 \texttt{$X$ * $Y$} &    multiplication \\ \hline 
 \texttt{$X$ / $Y$} &    division \\ \hline 
 \texttt{$X$ // $Y$} &    integer division, truncated \\ \hline 
 \texttt{$X$ /> $Y$}  &  integer division (ceiling($X$ / $Y$)) \\ \hline
 \texttt{$X$ /< $Y$}  &  integer division (floor($X$ / $Y$)) \\ \hline
 \texttt{$X$ div $Y$} &   integer division, floored \\ \hline
 \texttt{$X$ mod $Y$} &   modulo, same as $X$ - floor($X$ div $Y$) * $Y$ \\ \hline 
 \texttt{$X$ rem $Y$} &  remainder ($X$ - ($X$ // $Y$) * $Y$) \\ \hline 
 \texttt{$X$ + $Y$} & addition \\ \hline 
 \texttt{$X$ - $Y$} &   subtraction \\ \hline 
 \texttt{$X$ >> $Y$}  &  right shift \\ \hline 
 \texttt{$X$ << $Y$}  &  left shift \\ \hline 
 {\tt $X$ \verb+/\+ $Y$}  &   bitwise and \\ \hline 
 {\tt $X$ \verb+^+ $Y$} &   bitwise xor \\ \hline
 {\tt $X$ \verb+\/+ $Y$}  &   bitwise or \\ \hline 
 {\tt $From$ \verb+..+ $Step$ \verb+..+ $To$}  &   A range (list) of numbers with a step \\ \hline 
 {\tt $From$ \verb+..+ $To$}  &   A range (list) of numbers with step 1 \\ \hline
 {\tt $X$ \verb+=:=+ $Y$}  &   pretty much (numerically) equal \\ \hline
\end{tabular}
\end{center}
\end{table}

In addition to the numeric operators, the \texttt{basic} module also provides the following built-ins for numbers\index{number}:

\begin{itemize}
\item \texttt{between($From$,$To$,$X$)}\index{\texttt{between/3}} (nondet): If $X$ is bound to a number, then this predicate determines whether $X$ is between $From$ and $To$.  Otherwise, if $X$ is unbound, then this predicate nondeterministically selects $X$ from the numbers that are between $From$ and $To$ with step 1. It is the same as \texttt{member($X$,[$E$ : $E$ in $From$..$To$])}, but it does not create the list.
\item \texttt{between($From$,$Step$,$To$,$X$)}\index{\texttt{between/4}} (nondet): This predicate nondeterministically selects $X$ from the numbers that are between $From$ and $To$ with $Step$, where $From$, $To$, and $Step$ must be numbers. It is the same as \texttt{member($X$,[$E$ : $E$ in $From$..$Step$..$To$])}, but it does not create the list.
\item \texttt{bigint($Term$)}\index{\texttt{bigint/1}}: This predicate is true if $Term$ is a big integer.
\item \texttt{float($Term$)}\index{\texttt{float/1}}: This predicate is true if $Term$ is a real number\index{number}.
\item \texttt{int($Term$)}\index{\texttt{int/1}}: This predicate is true if $Term$ is an integer.
\item \texttt{integer($Term$)}\index{\texttt{integer/1}}: The same as \texttt{int($Term$)}.
\item \texttt{max($X$,$Y$) = $Val$}\index{\texttt{max/2}}: This function returns the maximum of $X$ and $Y$, where $X$ and $Y$ are terms.
\item \texttt{maxint\_small() = $Int$}\index{\texttt{maxint\_small/0}}: This function returns the maximum integer that is represented in one word. All integers that are greater than this integer are represented as \textit{big integers}.
\item \texttt{min($X$,$Y$) = $Val$}\index{\texttt{min/2}}: This function returns the minimum of $X$ and $Y$, where $X$ and $Y$ are terms.
\item \texttt{minint\_small() = $Int$}\index{\texttt{minint\_small/0}}: This function returns the minimum integer that is represented in one word. All integers that are smaller than this integer are represented as \textit{big integers}.
\item \texttt{number($Term$)}\index{\texttt{number/1}}: This predicate is true if $Term$ is a number\index{number}.
\item \texttt{number\_chars($Num$) = $String$}\index{\texttt{number\_chars/1}}: This function returns a list\index{list} of characters of $Num$. This function is the same as \texttt{to\_fstring("\%d",$Num$)}\index{\texttt{to\_fstring}} if $Num$ is an integer\index{integer}, and the same as \texttt{to\_fstring("\%f",$Num$)}\index{\texttt{to\_fstring}} if $Num$ is a real number\index{number}.
\item \texttt{number\_codes($Num$) = $List$}\index{\texttt{number\_codes/1}}: This function returns a list\index{list} of codes of the characters of $Num$. It is the same as \texttt{number\_chars($Num$).to\_codes()}\index{\texttt{number\_chars/1}}\index{\texttt{to\_codes/1}}.
\item \texttt{real($Term$)}\index{\texttt{real/1}}: This predicate is the same as \texttt{float($Term$)}\index{\texttt{float/1}}.
\item \texttt{to\_binary\_string($Int$) = $String$}\index{\texttt{to\_binary\_string/1}}: This function returns the binary representation of the integer\index{integer} $Int$ as a string\index{string}.
\item \texttt{to\_float($NS$) = $Real$}\index{\texttt{to\_float/1}}: This function is the same as \texttt{$NS$*1.0} if $NS$ is a number, and the same as \texttt{parse\_term($NS$)} if $NS$ is a string of digits.
\item \texttt{to\_hex\_string($Int$) = $String$}\index{\texttt{to\_hex\_string/1}}: This function returns the hexadecimal representation of the integer\index{integer} $Int$ as a string\index{string}.
\item \texttt{to\_int($ANS$) = $Int$}\index{\texttt{to\_int/1}}: This function is the same as \texttt{truncate($ANS$)}\index{\texttt{truncate/1}} in the \texttt{math} module if $ANS$ is a number, the same as \texttt{ord($ANS$)-ord('0')} if $ANS$ is a digit character, and the same as \texttt{parse\_term($ANS$)} if $ANS$ is a string.
\item \texttt{to\_integer($ANS$) = $Int$}\index{\texttt{to\_integer/1}}: This function is the same as \texttt{to\_int($ANS$)}.
\item \texttt{to\_number($ANS$) = $Num$}\index{\texttt{to\_number/1}}: This function is the same as $ANS$ if $ANS$ is a number, the same as \texttt{ord($ANS$)-ord('0')} if $ANS$ is a digit character, and the same as \texttt{parse\_term($ANS$)} if $ANS$ is a string.
\item \texttt{to\_oct\_string($Int$) = $String$}\index{\texttt{to\_oct\_string/1}}:  This function returns the octal representation of the integer $Int$ as a string\index{string}.
\item \texttt{to\_radix\_string($Int$,$Base$) = $String$}\index{\texttt{to\_radix\_string/2}}:  This function returns the representation of the integer $Int$ of the numeral $Base$ as a string\index{string}, where $Base$ must be greater than 1 and less than 37. The call \texttt{to\_oct\_string($Int$)} is the same as \texttt{to\_radix\_string($Int$,8)}.
\item \texttt{to\_real($NS$) = $Real$}\index{\texttt{to\_real/1}}: This function is the same as \texttt{to\_float($NS$)}.
\end{itemize}
The \texttt{math} module provides more numeric functions.  See Appendix \ref{chapter:math}.

\section{Compound Terms}
A compound term\index{compound value} can be a \emph{list}\index{list} or a \emph{structure}\index{structure}. Components of compound terms\index{compound value} can be accessed with subscripts. Let $X$ be a variable that references a compound value\index{compound value}, and let $I$ be an integer expression that represents a subscript. The index notation \texttt{$X$[$I$]} is a special function that returns the $I$th component of $X$ if $I$ is an integer or a list of components if $I$ is a range in the form of $l..u$, counting from the beginning. Subscripts begin at $1$, meaning that $X$[$1$] is the first component of $X$. An index notation can take multiple subscripts. For example, the expression \texttt{X[1,2]} is the same as \texttt{T[2]}, where \texttt{T} is a temporary variable that references the component that is returned by \texttt{X[1]}. The predicate \texttt{compound($Term$)}\index{\texttt{compound/1}} is true if $Term$ is a compound term\index{compound value}.

\subsection{\label{subsec:lists}Lists}
A list\index{list} takes the form \texttt{[$t_1$,$\ldots$,$t_{n}$]}, where each $t_i$ ($1\le i \le n$) is a term. Let $L$ be a list\index{list}. The expression \texttt{$L$.length}\index{\texttt{length/1}}, which is the same as the functions \texttt{get($L$,length)}\index{\texttt{get/2}} and \texttt{length($L$)}\index{\texttt{length/1}}, returns the length of $L$. Note that a list is represented internally as a singly-linked list.  Also note that the length of a list is not stored in memory; instead, it is recomputed each time that the function \texttt{length} is called.

The symbol \verb+'|'+ is not an operator, but a separator that separates the first element (so-called \emph{car}\index{car}) from the rest of the list\index{list} (so-called \emph{cdr}\index{cdr}). The \emph{cons}\index{cons} notation {\tt [$H$\verb+|+$T$]} can occur in a pattern or in an expression. When it occurs in a pattern, it matches any list\index{list} in which $H$ matches the car\index{car} and $T$ matches the cdr\index{cdr}. When it occurs in an expression, it builds a list\index{list} from $H$ and $T$. The notation {\tt [$A_1$,$A_2$,$\ldots$,$A_n$\verb+|+$T$]} is a shorthand for {\tt [$A_1$\verb+|+[$A_2$\verb+|+$\ldots$[$A_n$\verb+|+$T$]$\ldots$]}. So \texttt{[a,b,c]} is the same as \texttt{[a|[b|[c|[]]]]}.


The \texttt{basic} module provides the following built-ins on lists, most of which are overloaded for strings (\ref{subsec:strings}) and arrays (see \ref{subsec:arrays}).
\begin{itemize}
\item \texttt{$List_1$ ++ $List_2$ = $List$}: This function returns the concatenated list of $List_1$ and $List_2$. 
\item \texttt{append($X$,$Y$,$Z$)}\index{\texttt{append/3}} (nondet): This predicate is true if appending $Y$ to $X$ can create $Z$. This predicate may backtrack if $X$ is not a complete list.\footnote{A list is \emph{complete} \index{complete list} if it is empty, or if its tail is complete. For example, \texttt{[a,b,c]} and \texttt{[X,Y,Z]} are complete, but \texttt{[a,b|T]} is not complete if \texttt{T} is a variable.}

\item \texttt{append($W$,$X$,$Y$,$Z$)}\index{\texttt{append/4}} (nondet): This predicate is defined as:
\begin{verbatim}
    append(W,X,Y,Z) => append(W,X,WX), append(WX,Y,Z).
\end{verbatim}

\item \texttt{avg($List$) = $Val$}\index{\texttt{avg/1}}: This function returns the average of all the elements in $List$. This function throws an exception if $List$ is not a list or any of the elements is not a number. 

\item \texttt{delete($List$,$X$) = $ResList$}\index{\texttt{delete/2}}: This function deletes the first occurrence of $X$ from $List$, returning the result in $ResList$. The built-in \verb+!=/2+ is used to test if two terms are different. No variables in $List$ or $X$ will be bound after this function call.
\item \texttt{delete\_all($List$,$X$) = $ResList$}\index{\texttt{delete\_all/2}}: This function deletes all occurrences of $X$ from $List$, returning the result in $ResList$. The built-in \verb+!=/2+ is used to test if two terms are different.
\item \texttt{first($List$) = $Term$}\index{\texttt{first/1}}: This function returns the first element of $List$. 
\item \texttt{flatten($List$) = $ResList$}\index{\texttt{flatten/1}}: This function flattens a list of nested lists into a list. For example, \texttt{flatten([[1],[2,[3]]])} returns \texttt{[1,2,3]}.
\item \texttt{head($List$) = $Term$}\index{\texttt{head/1}}: This function returns the head of the list $List$. For example, \texttt{head([1,2,3])} returns \texttt{1}.
\item \texttt{insert($List$,$Index$,$Elm$) = $ResList$}\index{\texttt{insert/3}}: This function inserts $Elm$ into $List$ at the index $Index$, returning the result in $ResList$. After insertion, the original $List$ is not changed, and $ResList$ is the same as \\ \texttt{$List$.slice(1,$Index$-1)++[$Elm$|$List$.slice($Index$,$List$.length)]}.
\item \texttt{insert\_all($List$,$Index$,$AList$) = $ResList$}\index{\texttt{insert\_all/3}}: This function inserts all of the elements in $AList$ into $List$ at the index $Index$, returning the result in $ResList$. After insertion, the original $List$ is not changed, and $ResList$ is the same as \\ \texttt{$List$.slice(1,$Index$-1)++$AList$++$List$.slice($Index$,$List$.length)}.

\item \texttt{insert\_ordered($List$,$Term$)}\index{\texttt{insert\_ordered/2}}: This function inserts $Term$ into the ordered list $List$, such that the resulting list remains sorted.

\item \texttt{insert\_ordered\_down($List$,$Term$)}\index{\texttt{insert\_ordered\_down/2}}: This function inserts $Term$ into the descendantly ordered list $List$, such that the resulting list remains sorted down.
\item \texttt{last($List$) = $Term$}\index{\texttt{last/1}}: This function returns the last element of $List$. 
\item \texttt{len($List$) = $Len$}\index{\texttt{len/1}}: This function returns the number of elements in $List$. Note that this function is overloaded in such a way that the argument can also be an atom, an array, or a structure.
\item \texttt{length($List$) = $Len$}\index{\texttt{length/1}}: This function is the same as \texttt{len($List$)}.
\item \texttt{list($Term$)}\index{\texttt{list/1}}: This predicate is true if $Term$ is a list\index{list}.
\item \texttt{max($List$) = $Val$}\index{\texttt{max/1}}: This function returns the maximum value that is in $List$, where $List$ is a list of terms. 
\item \texttt{membchk($Term$,$List$)}\index{\texttt{membchk/2}}: This predicate is true if $Term$ is an element of $List$. 
\item \texttt{member($Term$,$List$)}\index{\texttt{member/2}} (nondet): This predicate is true if $Term$ is an element of $List$.  When $Term$ is a variable, this predicate may backtrack, instantiating\index{instantiated variable} $Term$ to different elements of $List$.
\item \texttt{min($List$) = $Val$}\index{\texttt{min/1}}: This function returns the minimum value that is in $List$, where $List$ is a list or an array of terms. 
\item \texttt{new\_list($N$) = $List$}\index{\texttt{new\_list/1}}: This function creates a new list that has $N$ free variable\index{free variable} arguments. 
\item \texttt{new\_list($N$,$InitVal$) = $List$}\index{\texttt{new\_list/2}}: This function creates a new list that has $N$ arguments all initialized to $InitVal$. 

\item \texttt{nth($Index$,$List$,$Elem$)}\index{\texttt{nth/3}} (nondet): This predicate is true when $Elem$ is the $Index$'th element of $List$.  Counting starts at 1. When $Index$ is a variable, this predicate may backtrack, instantiating $Index$ to a different integer between 1 and \texttt{len($List$)}.

\item \texttt{prod($List$) = $Val$}\index{\texttt{prod/1}}: This function returns the product of all of the values in $List$. 
\item \texttt{remove\_dups($List$) = $ResList$}\index{\texttt{remove\_dups/1}}: This function removes all duplicate values from $List$, retaining only the first occurrence of each value.  The result is returned in $ResList$. Note that an $O(n^2)$ algorithm is used in the implementation. For long lists, \texttt{sort\_remove\_dups} is faster than this function.
\item \texttt{reverse($List$) = $ResList$}\index{\texttt{reverse/1}}: This function reverses the order of the elements in $List$, returning the result in $ResList$. 
\item \texttt{select($X$,$List$,$ResList$)}\index{\texttt{select/3}} (nondet): This predicate nondeterministically selects an element $X$ from $List$, and binds $ResList$ to the list after $X$ is removed. On backtracking, it selects the next element.
\item \texttt{sort($List$) = $SList$}\index{\texttt{sort/1}}: This function sorts the elements of $List$ in ascending order, returning the result in $SList$. 
\item \texttt{sort($List$,$KeyIndex$) = $SList$}\index{\texttt{sort/2}}: This function sorts the elements of $List$ by the key index $KeyIndex$ in ascending order, returning the result in $SList$. The elements of $List$ must be compound values and $KeyIndex$ must be a positive integer that does not exceed the length of any of the elements of $List$. In particular, if an element is a list, then $KeyIndex$ must be either 1 or 2. This function is defined as follows:
\begin{verbatim}
    sort(List,KeyIndex) = SList =>
        List1 = [(A, E) : E in List, arg(KeyIndex,E,A)],
        List2 = sort(List1),
        SList = [E : (_,E) in List2].
\end{verbatim}

\item \texttt{sort\_remove\_dups($List$) = $SList$}\index{\texttt{sort\_remove\_dups/1}}: This function is the same as the following, but is faster.
\begin{tabbing}
aa \= aaa \= aaa \= aaa \=aaa \= aaa \= aaa \= aaa \kill
\> \texttt{sort($List$).remove\_dups()}
\end{tabbing}

\item \texttt{sort\_remove\_dups($List$,$KeyIndex$) = $SList$}\index{\texttt{sort\_remove\_dups/2}}: This function is the same as the following, but is faster.
\begin{tabbing}
aa \= aaa \= aaa \= aaa \=aaa \= aaa \= aaa \= aaa \kill
\> \texttt{sort($List$,$KeyIndex$).remove\_dups()}
\end{tabbing}

\item \texttt{sort\_down($List$) = $SList$}\index{\texttt{sort\_down/1}}: This function sorts the elements of $List$ in descending order, returning the result in $SList$.

\item \texttt{sort\_down($List$,$KeyIndex$) = $SList$}\index{\texttt{sort\_down/1}}: This function sorts the elements of $List$ by the key index $KeyIndex$ in descending order, returning the result in $SList$.

\item \texttt{sort\_down\_remove\_dups($List$) = $SList$}\index{\texttt{sort\_down\_remove\_dups/1}}: This function is the same as the following, but is faster.
\begin{tabbing}
aa \= aaa \= aaa \= aaa \=aaa \= aaa \= aaa \= aaa \kill
\> \texttt{sort\_down($List$).remove\_dups()}
\end{tabbing}

\item \texttt{sort\_down\_remove\_dups($List$,$KeyIndex$) = $SList$}\index{\texttt{sort\_down\_remove\_dups/1}}: This function is the same as the following, but is faster.
\begin{tabbing}
aa \= aaa \= aaa \= aaa \=aaa \= aaa \= aaa \= aaa \kill
\> \texttt{sort\_down($List$,$KeyIndex$).remove\_dups()}
\end{tabbing}

\item \texttt{slice($List$,$From$,$To$) = $SList$}\index{\texttt{slice/3}}: This function returns the sliced list of $List$ from index $From$ through index $To$. $From$ must not be less than 1. It is the same as the index notation $List$[$From$..$To$].

\item \texttt{slice($List$,$From$) = $SList$}\index{\texttt{slice/2}}: This function is the same as the following.
\begin{tabbing}
aa \= aaa \= aaa \= aaa \=aaa \= aaa \= aaa \= aaa \kill
\> \texttt{slice($List$,$From$,$List$.length)}
\end{tabbing}

\item \texttt{sum($List$) = $Val$}\index{\texttt{sum/1}}: This function returns the sum of all of the values in $List$. 
\item \texttt{tail($List$) = $Term$}\index{\texttt{tail/1}}: This function returns the tail of the list $List$.  For example, the call \texttt{tail([1,2,3])} returns \texttt{[2,3]}.
\item \texttt{to\_array($List$) = $Array$}\index{\texttt{to\_array/1}}: This function converts the list\index{list} $List$ to an array\index{array}.  The elements of the array\index{array} are in the same order as the elements of the list.
\item \texttt{zip($List_1$,$List_2$,$\ldots$,$List_n$) = $List$}\index{\texttt{zip}}: This function makes a list\index{list} of array tuples.  The $j$th tuple in the list takes the form \texttt{\{$E_{1j},\ldots,E_{nj}$\}}, where $E_{ij}$ is the $j$th element in $List_i$. In the current implementation, $n$ can be 2, 3, or 4.

\end{itemize}

\subsection{\label{subsec:strings}Strings}
A {\emph string}\index{string} is represented as a list\index{list} of single-character atoms\index{atom}. For example, the string\index{string} \texttt{"hello"} is the same as the list\index{list} \texttt{[h,e,l,l,o]}. In addition to the built-ins on lists\index{list}, the following built-ins are provided for strings\index{string}:
\begin{itemize}
\item \texttt{string($Term$)}\index{\texttt{string/1}}: This predicate is true if $Term$ is a string\index{string}. 
\item \texttt{to\_lowercase($String$) = $LString$}\index{\texttt{to\_lowercase/1}}: This function converts all uppercase alphabetic characters into lowercase characters, returning the result in $LString$.
\item \texttt{to\_uppercase($String$) = $UString$}\index{\texttt{to\_uppercase/1}}: This function converts all lowercase alphabetic characters into uppercase characters, returning the result in $UString$.
\end{itemize}

\subsection{Structures}
A structure\index{structure} takes the form \texttt{\$$s$($t_1$,$\ldots$,$t_{n}$)}, where $s$ is an atom, and $n$ is called the \emph{arity}\index{arity} of the structure\index{structure}. The dollar symbol is used to distinguish a structure\index{structure} from a function call. The \emph{functor}\index{functor} of a structure\index{structure} comprises the name and the arity\index{arity} of the structure\index{structure}. 

The following types of structures\index{structure} can never denote functions, meaning that they do not need to be preceded by a \$ symbol.
\begin{tabbing}
aa \= aaa \= aaa \= aaa \=aaa \= aaa \= aaa \= aaa \kill
\> Goals:  \>  \> \> \> \> \> \texttt{(a,b)},\ \texttt{(a;b)},\ \texttt{not a},\ \texttt{X = Y},\ \verb-X != 100-,\ \verb+X > 1+ \\
\> Constraints:  \>  \> \> \> \> \> \verb-X+Y #= 100-,\ \verb+X #!= 1+ \\
\> Arrays:  \>  \> \> \> \> \> \verb+{2,3,4}+,\ \verb+{P1,P2,P3}+ \\
% \> Lambda:  \>  \> \> \> \> \> \texttt{lambda([X, Y], X + Y)}
\end{tabbing}
Picat disallows creation of the following types of structures\index{structure}:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> Dot notations:  \>  \> \> \> \> \> \texttt{math.pi},\ \texttt{my\_module.f(a)} \\
\> Index notations:  \>  \> \> \> \> \> \texttt{X[1]+2}\, \texttt{X[Y[I]]} \\
\> Assignments:  \>  \> \> \> \> \> \texttt{X := Y+Z},\ \texttt{X := X+1} \\
\> Ranges:  \>  \> \> \> \> \> \texttt{1..10},\ \texttt{1..2..10} \\
\> List comprehensions:  \>  \> \> \> \> \> \texttt{[X : X in 1..5]} \\
\> Array comprehensions:  \>  \> \> \> \> \> \texttt{\{X : X in 1..5\}} \\
\> If:  \>  \> \> \> \> \> \texttt{if (X > Y) Z = X else Z = Y end} \\
\> Loops:  \>  \> \> \> \> \> \texttt{foreach (X in L) writeln(X) end } 
\end{tabbing}
The compiler will report a syntax error when it encounters any of these expressions within a term constructor.

The following built-ins are provided for structures\index{structure}:
\begin{itemize}
\item \texttt{$T$\ =..\ $L$}\index{{\verb+=../2+}}: The name and the arguments of $T$ comprise the list $L$. This predicate extracts the name and arguments of $T$ when $T$ is instantiated, and constructs $T$ from the list $L$ when $L$ is instantiated.

\item \texttt{arg($I$,$T$,$A$)}\index{\texttt{arg/3}}: The $I$th argument of the term $T$ is $A$. This predicate is the equivalent to: $X$\ =\ $T$,\ $A$\ =\ $X[I]$, except when $I$ is 0 or $T$ is a list. When $I$ is 0, the call fails. When $T$ is a list, only two indices, namely 1 and 2, are acceptable. For $I$ = 1, $A$ is unified with the car of the list, and for $I$ = 2, $A$ is unified with the cdr of the list.
\item \texttt{arity($Struct$) = $Arity$}\index{\texttt{arity/1}}: This function returns the arity of $Struct$, which must be a structure.

\item \texttt{functor($T$,$F$,$N$)}\index{\texttt{functor/3}}: The principal functor of the term $T$ has the name $F$ and the arity $N$. This predicate extracts the functor $F/N$ of $T$ when $T$ is instantiated, and constructs a term $T$ of the given functor $F/N$ when $T$ is a variable.

\item \texttt{len($Struct$) = $Arity$}\index{\texttt{len/1}}: This function is the same as \texttt{arity($Struct$)}.
\item \texttt{name($Struct$) = $Name$}\index{\texttt{name/1}}: This function returns the name of $Struct$.
\item \texttt{new\_struct($Name$,$IntOrList$) = $Struct$}\index{\texttt{new\_struct/2}}: This function creates a structure\index{structure} that has the name $Name$.  If $IntOrList$ is an integer, $N$, then the structure\index{structure} has $N$ free variable\index{free variable} arguments.  Otherwise, if $IntOrList$ is a list\index{list}, then the structure\index{structure} contains the elements in the list\index{list}.  
\item \texttt{struct($Term$)}\index{\texttt{struct/1}}: This predicate is true if $Term$ is a structure\index{structure}.
\item \texttt{to\_list($Struct$) = $List$}\index{\texttt{to\_list/1}}: This function returns a list\index{list} of the components of the structure\index{structure} $Struct$.
\end{itemize}

\subsection{\label{subsec:arrays}Arrays}
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{'\{\}'} and arity\index{arity} $n$. Note that, unlike a list, an array always has its length stored in memory, so the function \texttt{length($Array$)} always takes constant time. Also note that Picat supports constant-time access of array elements, so the index notation \texttt{A[I]} takes constant time when $I$ is an integer. 

In addition to the built-ins for structures\index{structure}, the following built-ins are provided for arrays\index{array}:
\begin{itemize}
\item \texttt{array($Term$)}\index{\texttt{array/1}}: This predicate is true if $Term$ is an array.
\item \texttt{new\_array($D_1$,$\ldots$,$D_n$) = $Arr$}\index{\texttt{new\_array}}: This function creates an n-dimensional array, where each $D_i$ is an integer expression that specifies the size of a dimension. In the current implementation, $n$ cannot exceed 10.
\end{itemize}

The following built-ins, which are originally provided for lists (see \ref{subsec:lists}), are overloaded for arrays:
\begin{itemize}
\item \texttt{$Array_1$ ++ $Array_2$ = $Array$}
\item \texttt{avg($Array$) = $Val$}\index{\texttt{avg/1}}
\item \texttt{first($Array$) = $Term$}\index{\texttt{first/1}}
\item \texttt{last($Array$) = $Term$}\index{\texttt{last/1}}
\item \texttt{len($Array$) = $Len$}\index{\texttt{len/1}}
\item \texttt{length($Array$) = $Len$}\index{\texttt{length/1}}
\item \texttt{max($Array$) = $Val$}\index{\texttt{max/1}}
\item \texttt{min($Array$) = $Val$}\index{\texttt{min/1}}
\item \texttt{nth($Index$,$List$,$Elem$)}\index{\texttt{nth/3}} (nondet)
\item \texttt{prod($Array$) = $Val$}\index{\texttt{prod/1}}
\item \texttt{reverse($Array$) = $ResArray$}\index{\texttt{reverse/1}}
\item \texttt{slice($Array$,$From$,$To$) = $SArray$}\index{\texttt{slice/3}}
\item \texttt{slice($Array$,$From$) = $SArray$}\index{\texttt{slice/2}}
\item \texttt{sum($Array$) = $Val$}\index{\texttt{max/1}}
\item \texttt{sort($Array$) = $SArray$}\index{\texttt{sort/1}}
\item \texttt{sort($Array$,$KeyIndex$) = $SArray$}\index{\texttt{sort/2}}
\item \texttt{sort\_remove\_dups($Array$) = $SArray$}\index{\texttt{sort\_remove\_dups/1}}
\item \texttt{sort\_remove\_dups($Array$,$KeyIndex$) = $SArray$}\index{\texttt{sort\_remove\_dups/2}}
\item \texttt{sort\_down($Array$) = $SArray$}\index{\texttt{sort\_down/1}}
\item \texttt{sort\_down($Array$,$KeyIndex$) = $SArray$}\index{\texttt{sort\_down/1}}
\item \texttt{sort\_down\_remove\_dups($Array$) = $SArray$}\index{\texttt{sort\_down\_remove\_dups/1}}
\item \texttt{sort\_down\_remove\_dups($Array$,$KeyIndex$) = $SArray$}\index{\texttt{sort\_down\_remove\_dups/1}}
\end{itemize}
Note that many of the overloaded built-ins for arrays are not implemented efficiently, but are provided for convenience. For example, \texttt{sort(Array)} is implemented as follows:
\begin{verbatim}
    sort(Array) = Array.to_list().sort().to_array().
\end{verbatim}

\subsection{Maps}
A \emph{map}\index{map} is a hash-table that is represented as a structure\index{structure} that contains a set of key-value pairs. The functor\index{functor} of the structure\index{structure} that is used for a map\index{map} is not important.  An implementation may ban access to the name and the arity\index{arity} of the structure\index{structure} of a map\index{map}. Maps\index{map} must be created with the built-in function \texttt{new\_map}\index{\texttt{new\_map/1}}, unless they are prebuilt (see Section \ref{prebuiltmaps}). In addition to the built-ins for structures\index{structure}, the following built-ins are provided for maps\index{map}:
\begin{itemize}
\item \texttt{clear($Map$)}\index{\texttt{clear/1}}: This predicate clears the map $Map$. It throws an error if $Map$ is not a map.
\item \texttt{del($Map$,$Key$)}\index{\texttt{del/2}}: This predicate deletes from $Map$ the pair that has the key $Key$. It throws an error if $Map$ is not a map. It does nothing if $Map$ does not contain a pair with $Key$.
\item \texttt{get($Map$,$Key$) = $Val$}\index{\texttt{get/2}}: This function returns \texttt{$Val$} of the key-value pair \texttt{$Key$$=$$Val$} in \texttt{$Map$}. It throws an error if $Map$ does not contain the key $Key$.
\item \texttt{get($Map$,$Key$,$DefaultVal$) = $Val$}\index{\texttt{get/3}}: This function returns \texttt{$Val$} of the key-value pair \texttt{$Key$$=$$Val$} in \texttt{$Map$}. It returns $DefaultVal$ if $Map$ does not contain $Key$.
\item \texttt{has\_key($Map$,$Key$)}\index{\texttt{has\_key/2}}: This predicate is true if $Map$ contains a pair with $Key$. 
\item \texttt{keys($X$) = $List$}\index{\texttt{keys/1}}: This function returns the list of keys of the pairs in $Map$.
\item \texttt{map($Term$)}\index{\texttt{map/1}}: This predicate is true if $Term$ is a map\index{map}. 
\item \texttt{map\_to\_list($Map$) = $PairsList$}\index{\texttt{map\_to\_list/1}}: This function returns a list\index{list} of \texttt{$Key$$=$$Val$} pairs that constitute $Map$. 
\item \texttt{new\_map($IntOrPairsList$) = $Map$}\index{\texttt{new\_map/1}}: This function creates a map\index{map} with an initial capacity or an initial list of pairs.
\item \texttt{new\_map($N$,$PairsList$) = $Map$}\index{\texttt{new\_map/2}}: This function creates a map\index{map} with the initial capacity $N$, the initial list of pairs $PairsList$, where each pair has the form \texttt{$Key$$=$$Val$}.
\item \texttt{put($Map$,$Key$,$Val$)}\index{\texttt{put/3}}: This predicate attaches the key-value pair \texttt{$Key$$=$$Val$} to \texttt{$Map$}, where \texttt{$Key$} is a non-variable term, and \texttt{$Val$} is any term. 
\item \texttt{put($Map$,$Key$)}\index{\texttt{put/2}}: This predicate is the same as \texttt{put($Map$,$Key$, not\_a\_value)}.
\item \texttt{values($Map$) = $List$}\index{\texttt{values/1}}: This function returns the list\index{list} of values of the pairs in $Map$.
\item \texttt{size($Map$) = $Size$}\index{\texttt{size/1}}: This function returns the number of pairs in $Map$.
\end{itemize}
Most of the built-ins are overloaded for attributed variables\index{attributed variable}.

\subsection{Sets}
A set\index{set} is a map where every key is associated with the atom \texttt{not\_a\_value}. All of the built-ins for maps can be applied to sets. For example, the built-in predicate \texttt{has\_key($Set$,$Elm$)} tests if $Elm$ is in $Set$. In addition to the built-ins on maps, the following built-ins are provided for sets:
\begin{itemize}
\item \texttt{new\_set($IntOrKeysList$) = $Set$}\index{\texttt{new\_set/1}}: This function creates a set with an initial capacity or an initial list of keys.
\item \texttt{new\_set($N$,$KeysList$) = $Set$}\index{\texttt{new\_set/2}}: This function creates a set with the initial capacity $N$ and the initial list of keys $KeysList$.
\end{itemize}

\subsection{Heaps}
A heap\index{heap}\footnote{Note that a heap, as a data structure, is different from the heap area, in which data, including heap maps, are stored.} 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}. In a min-heap, the value at the root of each subtree is the minimum among all the values in the subtree. In a max-heap, the value at the root of each subtree is the maximum among all the values in the subtree.
\begin{itemize}
\item \texttt{heap\_is\_empty($Heap$)}\index{\texttt{heap\_is\_empty/1}}: This predicate is true if $Heap$ is empty.
\item \texttt{heap\_pop($Heap$) = $Elm$}\index{\texttt{heap\_pop/1}}: This function removes the root element from the heap, and returns the element. As the function updates the heap, it is not pure. The update will be undone when execution backtracks over the call.
\item \texttt{heap\_push($Heap$,$Elm$)}\index{\texttt{heap\_push/2}}: This predicate pushes $Elm$ into $Heap$ in a way that maintains the heap property. The update to $Heap$ will be undone when execution backtracks over the call.
\item \texttt{heap\_size($Heap$) = $Size$}\index{\texttt{heap\_size/1}}: This function returns the size of $Heap$.
\item \texttt{heap\_to\_list($Heap$) = $List$}\index{\texttt{heap\_to\_list/1}}: This function returns a list of the elements in $Heap$.
\item \texttt{heap\_top($Heap$) = $Elm$}\index{\texttt{heap\_top/1}}: This function returns the element at the root of the heap. If $Heap$ is a min-heap, then the element is guaranteed to be the minimum, and if $Heap$ is a max-heap, then the element is guaranteed to be the maximum.
\item \texttt{new\_max\_heap($IntOrList$) = $Heap$}\index{\texttt{new\_max\_heap/1}}: This function creates a max-heap.  If $IntOrList$ is an integer, then it indicates the capacity.  Otherwise, if $IntOrList$ is a list, then the max-heap contains the elements in the list in an order that maintains the heap property.
\item \texttt{new\_min\_heap($IntOrList$) = $Heap$}\index{\texttt{new\_min\_heap/1}}: This function creates a min-heap.  If $IntOrList$ is an integer, then it indicates the capacity.  Otherwise, if $IntOrList$ is a list, then the min-heap contains the elements in the list in an order that maintains the heap property.
\end{itemize}

\subsection*{Example}
\begin{verbatim}
main =>
    L = [1,3,2,4,5,3,6],
    H = new_min_heap(L),
    N = H.heap_size(),
    S = [H.heap_pop() : _ in 1..N],
    println(S).
\end{verbatim}

\section{\label{sec:unification}Equality Testing, Unification, and Term Comparison}
The equality test \texttt{$T_1$ == $T_2$} \index{{\verb+==/2+}} is true if term $T_1$ and term $T_2$ are identical. Two variables are identical if they are aliases. Two primitive values\index{primitive value} are identical if they have the same type and the same internal representation. Two lists\index{list} are identical if the cars\index{car} are identical and the cdrs\index{cdr} are identical. Two structures\index{structure} are identical if their functors\index{functor} are the same and their components are pairwise identical. The inequality test \texttt{$T_1$ !== $T_2$}  is the same as \texttt{not $T_1$ == $T_2$}.  Note that two terms can be identical even if they are stored in different memory locations.  Also note that it takes linear time in the worst case to test whether two terms are identical, unlike in C-family languages, in which the equality test operator \texttt{==} only compares addresses.

The unification \texttt{$T_1$ = $T_2$} \index{{\verb+=/2+}} is true if term $T_1$ and term $T_2$ are already identical, or if they can be made identical by instantiating\index{instantiated variable} the variables in the terms. The built-in \texttt{$T_1$ != $T_2$}  is true if term $T_1$ and term $T_2$ are not unifiable. The predicate \texttt{bind\_vars($Term$,$Val$)}\index{\texttt{bind\_vars/2}} binds all of the variables in $Term$ to $Val$.

\subsection*{Example}
\begin{verbatim}
    Picat> X = 1
    X = 1
    Picat> $f(a,b) = $f(a,b)
    yes
    Picat> [H|T] = [a,b,c]
    H = a
    T = [b,c]
    Picat> $f(X,b) = $f(a,Y)
    X = a
    Y = b
    Picat> bind_vars({X,Y,Z},a)
    Picat> X = $f(X)
\end{verbatim}
The last query illustrates the \emph{occurs-check problem}\index{occurs-check problem}. When binding \texttt{X} to \texttt{f(X)}, Picat does not check if \texttt{X} occurs in \texttt{f(X)} for the sake of efficiency. This unification creates a cyclic term, which can never be printed.

When a unification's operands contain attributed variables\index{attributed variable}, the implementation is more complex. When a plain variable is unified with an attributed variable\index{attributed variable}, the plain variable is bound to the attributed variable\index{attributed variable}. When two attributed variables\index{attributed variable}, say $Y$ and $O$, where $Y$ is younger than $O$, are unified,  $Y$ is bound to $O$, but $Y$'s attributes are not copied to $O$. Since garbage collection does not preserve the seniority of terms, the result of the unification of two attributed variables\index{attributed variable} is normally unpredictable.

\subsection{Numerical Equality}
The numerical equality test \texttt{$T_1$ =:= $T_2$}\index{{\verb+=:=/2+}} is true if term $T_1$ and term $T_2$ are pretty much the same numerical value.  This means that $T1$ and $T2$ must both be numbers after evaluation.  Whereas the test \texttt{$T_1$ == $T_2$} fails if one number is an integer and one number is a real number, the test \texttt{$T_1$ =:= $T_2$} may succeed if the difference between $T_1$ and $T_2$ is less than 0.00000001.  Consider the following examples.
\subsection*{Example}

\begin{verbatim}
    
Picat> 1 == 1.0
no

Picat> 1 =:= 1.0
yes
\end{verbatim}
In the first query, $1$ is an integer, while $1.0$ is a real number, so the equality test fails.  However, the second query, which is a numerical equality test, succeeds.  

\begin{itemize}
\item \texttt{$T_1$ is $T_2$}\index{\texttt{is/2}}: If \texttt{$T_1$} is a variable, then the call binds the variable to the result of \texttt{$T_2$}, which must be a number after evaluation. If \texttt{$T_1$} is a non-variable expression, then the call is equivalent to \texttt{$T_1$ =:= $T_2$}.

\item $T_1$ \verb+=\=+ $T_2$\index{{\verb+=\=/2+}}: The expression \texttt{$T_1$} is not numerically equal to \texttt{$T_2$}.
\end{itemize}

\subsection{Ordering of Terms}
Picat orders terms in the following way:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{var}\ $<$\ \texttt{number} \ $<$\ \texttt{atom} \ $<$\ \texttt{structure} and \texttt{array} \ $<$\ \texttt{list} and \texttt{string}
\end{tabbing}
Variables are ordered by their addresses. Note that the ordering of variables may change after garbage collection. Numbers are ordered by their numerical values. Atoms are ordered lexicographically. Structures are first ordered lexicographically by their names; if their names are the same, then they are ordered by their components. Arrays are ordered as structures with the special name '\{\}'. Lists and strings are ordered by their elements.

\begin{itemize}
\item \texttt{$Term1$ @< $Term2$}: The term $Term1$ precedes the term $Term2$ in the standard order. For example, \texttt{a @< b} succeeds.
\item \texttt{$Term1$ @=< $Term2$}: The term $Term1$ either precedes, or is identical to, the term $Term2$ in the standard order. For example, \texttt{a @=< b} succeeds.
\item \texttt{$Term1$ @<= $Term2$}: This is the same as \texttt{$Term1$ @=< $Term2$}.
\item \texttt{$Term1$ @> $Term2$}: The term $Term1$ follows the term $Term2$ in the standard order.
\item \texttt{$Term1$ @>= $Term2$}: The term $Term1$ either follows, or is identical to, the term $Term2$ in the standard order.
\end{itemize}

\section{Expressions}
Expressions are made from variables, values, operators, and function calls. Expressions differ from terms in the following ways: 
\begin{itemize}
\item An expression can contain dot notations, such as \texttt{math.pi}.
\item An expression can contain index notations, such as \texttt{X[I]}.
\item An expression can contain ranges, such as \texttt{1..2..100}.
\item An expression can contain list comprehensions, such as \texttt{[X : X in 1..100]}.
\item An expression can contain array comprehensions, such as \texttt{\{X : X in 1..100\}}.
\end{itemize}

A conditional expression, which takes the form \texttt{cond($Cond$,$Exp_1$,$Exp_2$)}, is a special kind of function call that returns the value of $Exp_1$ if the condition $Cond$ is true and the value of $Exp_2$ if $Cond$ is false.\index{\texttt{cond}}

Note that, except for conditional expressions in which the conditions are made of predicates, no expressions can contain predicates. A predicate is true or false, but never returns any value.


\section{Higher-order Predicates and Functions}
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 \texttt{basic} module has the following higher-order predicates and functions.

\begin{itemize}
\item \texttt{apply($S$,$Arg_1$,$\ldots$,$Arg_n$) = $Val$}\index{\texttt{apply}}:   $S$ is an atom or a structure.  This function calls the function that is named by $S$ with the arguments that are specified in $S$, together with extra arguments $Arg_1$, \ldots, $Arg_n$.  This function returns the value that $S$ returns.
\item \texttt{call($S$,$Arg_1$,$\ldots$,$Arg_n$)}\index{\texttt{call}}:  $S$ is an atom or a structure.  This predicate calls the predicate that is named by $S$ with the arguments that are specified in $S$, together with extra arguments $Arg_1$, \ldots, $Arg_n$.
\item \texttt{call\_cleanup($Call$,$Cleanup$)}\index{\texttt{call\_cleanup/2}}: This predicate is the same as \texttt{call($Call$)}, except that \texttt{$Cleanup$} is called when \texttt{$Call$} succeeds determinately (i.e., with no remaining choice point), when \texttt{$Call$} fails, or when \texttt{$Call$} raises an exception.
\item \texttt{catch($Call$,$Exception$,$Handler$)}\index{\texttt{catch/3}}: This predicate is the same as $Call$, except when an exception that matches $Exception$ is raised during the execution of $Call$. When such an exception is raised, all of the bindings that have been performed on variables in \texttt{$Call$} will be undone, and \texttt{$Handler$} will be executed to handle the exception.
\item \texttt{count\_all($Call$) = $Count$}\index{\texttt{count\_all/2}}: This function returns the number of all possible instances of \texttt{call($Call$)} that are true. For example, \texttt{count\_all(member(X,[1,2,3]))} returns 3.
\item \texttt{findall($Template$,$Call$) = $Answers$}\index{\texttt{findall/2}}: This function returns a list of all possible instances of \texttt{call($Call$)} that are true in the form of $Template$. Note that $Template$ is assumed to be a term without function calls, and that $Call$ is assumed to be a predicate call whose arguments can contain function calls. Also note that, like a loop, \texttt{findall} forms a name scope. For example, in \texttt{findall(f(X),p(X,g(Y)))}, \texttt{f(X)} is a term even though it is not preceded with \verb+$+; \texttt{g(Y)} is a function call; the variables \texttt{X} and \texttt{Y} are assumed to be local to \texttt{findall} if they do not occur before in the outer scope.
\item \texttt{find\_all($Template$,$Call$) = $Answers$}\index{\texttt{find\_all/2}}: This function is the same as the above function.
\item \texttt{freeze($X$,$Call$)}\index{\texttt{freeze/2}}: This predicate delays the evaluation of $Call$ until $X$ becomes a non-variable term.
\item \texttt{map($FuncOrList$,$ListOrFunc$) = $ResList$}\index{\texttt{map/2}}: This function applies a given function to every element of a given list and returns a list of the results. One of the arguments is a function, and the other is a list. The order of the arguments is not important. 
\item \texttt{map($Func$,$List1$,$List2$) = $ResList$}\index{\texttt{map/3}}: Let
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> $List1$ = \texttt{[$A_1$,$\ldots$,$A_n$]} and $List2$ = \texttt{[$B_1$,$\ldots$,$B_n$]}.
\end{tabbing}
This function applies the function $Func$ to every pair of elements $(A_i,B_i)$ by calling \texttt{apply($Func$,$A_i$,$B_i$)}, and returns a list of the results.
\item \texttt{maxof($Call$,$Objective$)}\index{\texttt{maxof/2}}: This predicate finds a satisfiable instance of $Call$, such that $Objective$ has the maximum value. Here, $Call$ is used as a generator, and $Objective$ is an expression to be maximized. For every satisfiable instance of $Call$, $Objective$ must be a ground expression. For \texttt{maxof}, search is restarted with a new bound each time that a better answer is found.
\item \texttt{maxof($Call$,$Objective$,$ReportCall$)}\index{\texttt{maxof/3}}: This is the same as \texttt{maxof($Call$,$Objective$)}, except that \texttt{call($ReportCall$)} is executed each time that an answer is found.
\item \texttt{maxof\_inc($Call$,$Objective$)}\index{\texttt{maxof\_inc/2}}: This is the same as \texttt{maxof($Call$,$Objective$)}, except that search continues rather than being restarted each time that a better solution is found.
\item \texttt{maxof\_inc($Call$,$Objective$,$ReportCall$)}\index{\texttt{maxof\_inc/3}}: This is the same as the previous predicate, except that \texttt{call($ReportCall$)} is executed each time that an answer is found.
\item \texttt{minof($Call$,$Objective$)}\index{\texttt{minof/2}}: This predicate finds a satisfiable instance of $Call$, such that $Objective$ has the minimum value. 
\item \texttt{minof($Call$,$Objective$,$ReportCall$)}\index{\texttt{minof/3}}: This is the same as \texttt{minof($Call$,$Objective$)}, except that \texttt{call($ReportCall$)} is executed each time that an answer is found.
\item \texttt{minof\_inc($Call$,$Objective$)}\index{\texttt{minof\_inc/2}}: This predicate is the same as \texttt{minof($Call$,$Objective$)}, except that search continues rather than being restarted each time that a better solution is found.
\item \texttt{minof\_inc($Call$,$Objective$,$ReportCall$)}\index{\texttt{minof\_inc/3}}: This predicate is the same as the previous one, except that \texttt{call($ReportCall$)} is executed each time that an answer is found.
\item \texttt{reduce($Func$,$List$) = $Res$}\index{\texttt{reduce/2}}: If $List$ is a list that contains only one element, this function returns the element. If $List$ contains at least two elements, then the first two elements $A_1$ and $A_2$ are replaced with \texttt{apply($Func$,$A_1$,$A_2$)}. This step is repeatedly applied to the list until the list contains a single element, which is the final value to be returned. The order of the arguments is not important, meaning that the first argument can be a list and the second one can be a function.
\item \texttt{reduce($Func$,$List$,$InitVal$) = $Res$}\index{\texttt{reduce/3}}: This function is the same as\\
 \texttt{reduce($Func$,[$InitVal$$|$$List$])}.
\end{itemize}


\section{\label{sec:otherbuiltins}Other Built-ins in the \texttt{basic} Module}
\begin{itemize}
\item \texttt{acyclic\_term($Term$)}\index{\texttt{acyclic\_term/1}}: This predicate is true if $Term$ is acyclic, meaning that $Term$ does not contain itself.
\item \texttt{and\_to\_list($Conj$) = $List$}\index{\texttt{and\_to\_list/1}}: This function converts $Conj$ in the form \texttt{($a_1$,$\ldots$,$a_n$)} into a list in the form \texttt{[$a_1$,$\ldots$,$a_n$]}.
\item \texttt{compare\_terms($Term_1$,$Term_2$) = $Res$}\index{\texttt{compare\_terms/2}}:  This function compares $Term_1$ and $Term_2$.  If $Term_1 < Term_2$, then this function returns $-1$.  If $Term_1 == Term_2$, then this function returns $0$.  Otherwise, $Term_1 > Term_2$, and this function returns $1$.
\item \texttt{different\_terms($Term_1$,$Term_2$)}\index{\texttt{different\_terms/2}}: This constraint ensures that $Term_1$ and $Term_2$ are different. This constraint is suspended when the arguments are not sufficiently instantiated\index{instantiated variable}.
\item \texttt{get\_global\_map() = $Map$}\index{\texttt{get\_global\_map/0}}: This function returns the global map\index{map}.
\item \texttt{get\_global\_map($ID$) = $Map$}\index{\texttt{get\_global\_map/1}}: This function returns the global map with the identifier $ID$, which must be a ground term.
\item \texttt{get\_heap\_map() = $Map$}\index{\texttt{get\_heap\_map/0}}: This function returns the default heap map\index{map}.
\item \texttt{get\_heap\_map($ID$) = $Map$}\index{\texttt{get\_heap\_map/1}}: This function returns the heap map with the identifier $ID$, which must be ground term.  
\item \texttt{get\_table\_map() = $Map$}\index{\texttt{get\_table\_map/0}}: This function returns the default table map. The table map is stored in the table area and both keys and values are hash-consed (i.e., common sub-terms are shared).
\item \texttt{get\_table\_map($ID$) = $Map$}\index{\texttt{get\_table\_map/1}}: This function returns the table map with the identifier $ID$, which must be a ground term. 
\item \texttt{ground($Term$)}\index{\texttt{ground/1}}: This predicate is true if $Term$ is ground\index{ground}.  A \emph{ground}\index{ground} term does not contain any variables.
\item \texttt{list\_to\_and($List$) = $Conj$}\index{\texttt{list\_to\_and/1}}: This function converts $List$ in the form \texttt{[$a_1$,$\ldots$,$a_n$]} into a term in the form \texttt{($a_1$,$\ldots$,$a_n$)}.
\item \texttt{number\_vars($Term$)}\index{\texttt{number\_vars/1}}: This predicate numbers the variables in $Term$ by using the integers starting from 0. Different variables receive different numberings, and the occurrences of the same variable all receive the same numbering.
\item \texttt{number\_vars($Term$,$N_0$) = $N_1$}\index{\texttt{number\_vars/2}}: This function numbers the variables in $Term$ by using the integers starting from $N_0$.  $N_1$ is the next integer that is available after $Term$ is numbered.  
\item \texttt{parse\_radix\_string($String$,$Base$) = $Int$}\index{\texttt{parse\_radix\_string/2}}: This function converts a radix $String$ of $Base$ into a decimal integer $Int$, where $Base$ must be greater than 1 and less than 37. For example, \texttt{parse\_radix\_string("101",2)} returns 5, which is the same as \texttt{parse\_term("0b101")}.
\item \texttt{parse\_term($String$,$Term$,$Vars$)}\index{\texttt{parse\_term/3}}: This predicate uses the Picat parser to extract a term $Term$ from $String$. $Vars$ is a list of pairs, where each pair has the form $Name$=$Var$. 
\item \texttt{parse\_term($String$) = $Term$}\index{\texttt{parse\_term/1}}: This function converts $String$ to a term.
\item \texttt{second($Compound$) = $Term$}\index{\texttt{second/1}}: This function returns the second argument of the compound term $Compound$.  
\item \texttt{subsumes($Term_1$,$Term_2$)}\index{\texttt{subsumes/2}}: This predicate is true if $Term_1$ subsumes $Term_2$.
\ignore{
\item \texttt{unnumber\_vars($Term_1$) = $Term_2$}\index{\texttt{unnumber\_vars/1}}: $Term_2$ is a copy of $Term_1$, with all numbered variables being replaced by Picat variables.  Different numbered variables are replaced by different Picat variables.
}
\item \texttt{variant($Term_1$,$Term_2$)}\index{\texttt{variant/2}}: This predicate is true if $Term_2$ is a variant of $Term_1$.
\item \texttt{vars($Term$) = $Vars$}\index{\texttt{vars/1}}: This function returns a list\index{list} of variables that occur in $Term$.
\end{itemize}
\ignore{
\end{document}
}
\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:predicates}Predicates and Functions}
In Picat, predicates\index{predicate} and functions\index{function} are defined with rules. Each rule is terminated by a dot (\verb+.+) followed by a white space or the newline character.

Picat has two types of pattern-matching rules: the \emph{non-backtrackable} rule\index{non-backtrackable rule} 
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> $Head, Cond\ $\verb+=>+$\ Body$. 
\end{tabbing}
and the \emph{backtrackable} rule\index{backtrackable rule} 
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> $Head, Cond\ $\verb+?=>+$\ Body$. 
\end{tabbing}
Picat also supports Prolog-style Horn clauses \index{Prolog}\index{Horn clause} and Definite Clause Grammar (DCG) rules \index{Definite Clause Grammar}\index{DCG rule} for predicate definitions. A Horn clause takes the form:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> $Head\ $\verb+:-+$\ Body$. 
\end{tabbing}
which can be written as $Head$ if $Body$ is \texttt{true}. A DCG rule takes the form:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> $Head\ $\verb+-->+$\ Body$. 
\end{tabbing}
A predicate definition that consists of Horn clauses can be preceded by an \emph{index declaration}, as described in Section \ref{section:horn}. Picat converts Horn clauses and DCG rules into pattern-matching rules.

\section{Predicates}
A \emph{predicate}\index{predicate} defines a relation, and can have zero, one, or multiple answers. Within a predicate\index{predicate}, the $Head$ is a \emph{pattern} in the form $p(t_1,\ldots,t_n)$, where $p$ is called the predicate\index{predicate} \emph{name}, and $n$ is called the \emph{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. $Cond$ cannot succeed more than once. The compiler converts $Cond$ to \texttt{once $Cond$}\index{\texttt{once/1}} if would otherwise be possible for $Cond$ to succeed more than once.

For a call $C$, if $C$ matches the pattern $p(t_1,\ldots,t_n)$ and $Cond$ is true, then 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$. However, if the used rule is backtrackable\index{backtrackable rule}, then the program will backtrack to $C$ once $Body$ fails, meaning that $Body$ will be rewritten back to $C$, and the next applicable rule will be tried on $C$. 

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

\subsection*{Example}
\begin{verbatim}
    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).
\end{verbatim}
The predicate \texttt{append(Xs,Ys,Zs)}\index{\texttt{append/3}} is true if the concatenation of \texttt{Xs} and \texttt{Ys} is \texttt{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 
\begin{verbatim}
    append([a,b],[c,d],L)
\end{verbatim}
this predicate can also be used to split a list nondeterministically into two sublists, as in the call \texttt{append(L1,L2,[a,b,c,d])}\index{\texttt{append/3}}; this predicate can even be called with three free variables, as in the call \texttt{append(L1,L2,L3)}\index{\texttt{append/3}}. 

The predicate \texttt{min\_max(L,Min,Max)} returns two answers through its arguments.  It binds \texttt{Min} to the minimum of list \texttt{L}, and binds \texttt{Max} to the maximum of list \texttt{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\index{tail recursion} version of this predicate that consumes constant space will be given below.


\section{Functions}
A \emph{function}\index{function} is a special kind of a predicate\index{predicate} that always succeeds with \emph{one} answer. Within a function\index{function}, the $Head$ is an equation $p(t_1,\ldots, t_n)$\verb+=+$X$, where $p$ is called the function\index{function} \emph{name}, and $X$ is an \emph{expression} that gives the return value. Functions\index{function} are defined with non-backtrackable rules\index{non-backtrackable rule} only.  

For a call $C$, if $C$ matches the pattern $p(t_1,\ldots,t_n)$ and $Cond$ is true, then the rule is said to be \emph{applicable} to $C$. When applying a rule to call $C$, Picat rewrites the equation $C$\verb+=+$X'$ into \texttt{($Body$, $X'$=$X$)}, where $X'$ is a newly introduced variable that holds the return value of $C$. 

Picat allows inclusion of \emph{function facts}\index{function fact} in the form {\tt $p$($t_1$,$\ldots$,$t_n$)\verb+=+$Exp$} in function\index{function} definitions. The function fact\index{function fact} {\tt $p$($t_1$,$\ldots$,$t_n$)\verb+=+$Exp$} is shorthand for the rule:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> {\tt $p$($t_1$,$\ldots$,$t_n$)\verb+=+$X$ \verb+=>+ $X\verb+=+Exp$.}
\end{tabbing}
where $X$ is a new variable.
 
Although all functions\index{function} can be defined as predicates\index{predicate}, it is preferable to define them as functions\index{function} for two reasons.  Firstly, functions\index{function} often lead to more compact expressions than predicates\index{predicate}, because arguments of function\index{function} calls can be other function\index{function} calls.  Secondly, functions\index{function} are easier to debug than predicates\index{predicate}, because functions\index{function} never fail and never return more than one answer. 

\subsection*{Example}
\begin{verbatim}
    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].
\end{verbatim}
The function \texttt{qequation(A,B,C)} returns the pair of roots of \texttt{A*X$^2$+B*X+C = 0}. If the discriminant \texttt{B*B-4*A*C} is negative, then an exception will be thrown. 

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

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

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

\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> \texttt{unresolved\_function\_call(rev(L))}.
\end{tabbing}

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

\subsection*{Example}
\begin{verbatim}
    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)].
\end{verbatim}
In the third rule, the as-pattern\index{as-pattern} \texttt{Ys@[Y|\_]} binds two variables: \texttt{Ys} references the second argument, and \texttt{Y} references the car\index{car} of the argument. The rule can be rewritten as follows without using any as-pattern\index{as-pattern}:
\begin{verbatim}
    merge([X|Xs],[Y|Ys]) = [X|Zs], X < Y => Zs = merge(Xs,[Y|Ys]). 
\end{verbatim}
Nevertheless, this version is less efficient, because the cons\index{cons} \texttt{[Y|Ys]} needs to be re-constructed.

\section{Goals}
In a rule, both the condition and the body are \emph{goals}\index{goal}. Queries that the users give to the interpreter are also goals\index{goal}. A goal\index{goal} can take one of the following forms:
\begin{itemize}
\item \texttt{true}\index{\texttt{true}}: This goal\index{goal} is always true.
\item \texttt{fail}\index{\texttt{fail}}: This goal\index{goal} is always false. When \texttt{fail}\index{\texttt{fail}} occurs in a condition, the condition is false, and the rule is never applicable. When \texttt{fail}\index{\texttt{fail}} occurs in a body, it causes execution to backtrack.
\item \texttt{false}\index{\texttt{false}}: This goal is the same as \texttt{fail}.
\item $p(t_1, \ldots, t_n)$: This goal\index{goal} is a predicate call. The arguments $t_1, \ldots, t_n$ are evaluated in the given order, and the resulting call is resolved using the rules in the predicate $p/n$. If the call succeeds, then variables in the call may get instantiated. Many built-in predicates\index{predicate} are written in infix notation. For example, \texttt{X = Y} is the same as \texttt{'='(X,Y)}.
\item \texttt{$P$, $Q$}: This goal\index{goal} is a conjunction of goal\index{goal} $P$ and goal\index{goal} $Q$. It is resolved by first resolving $P$, and then resolving $Q$. The goal\index{goal} is true if both $P$ and $Q$ are true. Note that the order is important: ($P$,$Q$) is in general not the same as ($Q$,$P$).
\item \texttt{$P$ $\&\&$ $Q$}: This is the same as \texttt{($P$,$Q$)}. 
\item \texttt{$P$; $Q$}: This goal\index{goal} is a disjunction of goal\index{goal} $P$ and goal\index{goal} $Q$. It is resolved by first resolving $P$. If $P$ is true, then the disjunction is true. If $P$ is false, then $Q$ is resolved. The disjunction is true if $Q$ is true. The disjunction is false if both $P$ and $Q$ are false. Note that a disjunction can succeed more than once. Note also that the order is important: ($P$; $Q$) is generally not the same as ($Q$; $P$).
\item \texttt{$P$ $|$$|$ $Q$}: This is the same as \texttt{($P$; $Q$)}.
\item \texttt{not $P$}\index{\texttt{not/1}}: This goal\index{goal} is the negation of $P$. It is false if $P$ is true, and true if $P$ is false.  Note a negation goal\index{goal} can never succeed more than once.  Also note that no variables can get instantiated, no matter whether the goal\index{goal} is true or false.
\item \verb-\+- \texttt{$P$}\index{{\verb-\+/1-}}: This is the same as \texttt{not $P$}.
\item \texttt{once $P$}\index{\texttt{once/1}}: This goal\index{goal} is the same as $P$, but can never succeed more than once.
\item \texttt{repeat}\index{\texttt{repeat/0}}: This predicate is defined as follows:
\begin{verbatim}
    repeat ?=> true.
    repeat => repeat.
\end{verbatim}
The \texttt{repeat}\index{\texttt{repeat/0}} predicate is often used to describe failure-driven loops\index{failure-driven loop}. For example, the query 
\begin{verbatim}
      repeat, writeln(a), fail
\end{verbatim} 
repeatedly outputs \texttt{'a'} until \texttt{ctrl-c} is typed.
\item \texttt{if}\index{if statement}: An if statement takes the form
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{if ($Cond_1$)} \\
\> \> $Goal_1$ \\
\> \texttt{elseif ($Cond_2$)} \\
\> \> $Goal_2$ \\
\> \> $\vdots$ \\
\> \texttt{elseif ($Cond_{n}$)} \\
\> \> $Goal_{n}$ \\
\> \texttt{else} \\
\> \> $Goal_{else}$ \\
\> \texttt{end}
\end{tabbing}
where the \texttt{elseif} and \texttt{else} clauses are optional. If the \texttt{else} clause is missing, then the else goal\index{goal} is assumed to be \texttt{true}. For the if statement, Picat finds the first condition $Cond_i$ that is true. If such a condition is found, then the truth value of the if statement is the same as $Goal_i$. If none of the conditions is true, then the truth value of the if statement is the same as $Goal_{else}$. Note that no condition can succeed more than once.\footnote{If $Cond_i$ is not enclosed in parentheses, then it must be followed by the keyword \texttt{then}.}
\ignore{
\item \texttt{try-catch}\index{\texttt{try}}: A \texttt{try-catch}\index{\texttt{try}} statement specifies a goal\index{goal} to try, the exceptions that need to be handled when they occur during the execution of the goal\index{goal}, and a clean-up goal\index{goal} that is executed no matter whether the goal\index{goal} succeeds, fails, or is terminated by an exception. The detailed syntax and semantics of the \texttt{try-catch}\index{\texttt{try}} statement will be given in Chapter \ref{chapter:exception} on Exceptions.
}
\item \texttt{throw $Exception$}\index{\texttt{throw/1}}: This predicate throws the term $Exception$. This predicate will be detailed in Chapter \ref{chapter:exception} on Exceptions.

\item \verb+!+\index{cut}: This special predicate, called a \textit{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. 

\item 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 \ref{chapter:loops}.
\end{itemize}

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

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


\subsection*{Example}
\begin{verbatim}
    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]).
\end{verbatim}
In the helper predicate \texttt{min\_max\_helper(L,CMin,Min,CMax,Max)}, \texttt{CMin} and \texttt{CMax} are accumulators\index{accumulator}: \texttt{CMin} is the current minimum value, and \texttt{CMax} is the current maximum value. When \texttt{L} is empty, the accumulators\index{accumulator} are returned by the unification calls \texttt{Min = CMin} and \texttt{Max = CMax}. When \texttt{L} is a cons\index{cons} \texttt{[H|T]}, the accumulators\index{accumulator} are updated: \texttt{CMin} changes to \texttt{min(CMin,H)}\index{\texttt{min/2}}, and \texttt{CMax} changes to \texttt{max(CMax,H)}\index{\texttt{max/2}}. The helper function \texttt{rev\_helper(L,R)} follows the same idea: it uses an accumulator\index{accumulator} list to hold, in reverse order, the elements that have been scanned. When \texttt{L} is empty, the accumulator\index{accumulator} is returned. When \texttt{L} is the cons\index{cons} \texttt{[X|Xs]}, the accumulator\index{accumulator} \texttt{R} changes to \texttt{[X|R]}.
\ignore{
\end{document}
}


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

\makeindex
\begin{document}

}
\chapter{Assignments and Loops\label{chapter:loops}}
This chapter discusses variable assignments\index{assignment}, loop constructs, and list and array comprehensions\index{list comprehension} in Picat.  It describes the \emph{scope}\index{scope} of an assigned\index{assignment} variable, indicating where the variable is defined, and where it is not defined.  Finally, it shows how assignments\index{assignment}, loops, and list comprehensions\index{list comprehension} are related, and how they are compiled.  

\section{Assignments}
Picat variables are \emph{single-assignment}\index{assignment}\index{single-assignment}, meaning that once a variable is bound to a value, the variable cannot be bound again.  In order to simulate imperative\index{imperative} language variables, Picat provides the assignment\index{assignment} operator \verb+:=+.  An assignment\index{assignment} takes the form $LHS $$:$$=$$ 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}

The compiler needs to give special consideration to the \emph{scope}\index{scope} of a variable.  The scope\index{scope} of a variable refers to the parts of a program where a variable occurs.  

Consider the \texttt{test} example.  This example binds \texttt{X} to $0$.  Then, the example tries to bind \texttt{X} to \texttt{X + 1}.  However, \texttt{X} is still in scope\index{scope}, meaning that \texttt{X} is already bound to $0$.  Since \texttt{X} cannot be bound again, the compiler must perform extra operations in order to manage assignments\index{assignment} that use the \texttt{:=} operator. 

In order to handle assignments\index{assignment}, Picat creates new variables at compile time.  In the \texttt{test} 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}.  All occurrences of \texttt{X} after the assignment\index{assignment} are replaced 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}

\subsection{If-Else}
This leads to the question: what does the compiler do if the code branches?  Consider the following code skeleton.
\subsection*{Example}
\begin{verbatim}
if_ex(Z) =>
    X = 1, Y = 2,
    if (Z > 0)
       X := X * Z    
    else
       Y := Y + Z
    end,
    println([X,Y]).
\end{verbatim}

The \texttt{if\_ex} example performs exactly one assignment\index{assignment}.  At compilation time, the compiler does not know whether or not \texttt{ Z$>$0} evaluates to \texttt{true}\index{\texttt{true}}.  Therefore, the compiler does not know whether to introduce a new variable for \texttt{X} or for \texttt{Y}.

Therefore, when an if-else statement\index{if statement} contains an assignment\index{assignment}, the compiler rewrites the if-else statement\index{if statement} as a predicate.  For example, the compiler rewrites the above example as follows:

\begin{verbatim}
if_ex(Z) => 
   X = 1, Y = 2, 
   p(X, Xout, Y, Yout, Z),
   println([Xout,Yout]).

p(Xin, Xout, Yin, Yout, Z), Z > 0 =>
   Xout = X * Z,
   Yout = Yin.
p(Xin, Xout, Yin, Yout, Z) =>
   Xout = Xin,
   Yout = Y + Z.
\end{verbatim}
One rule is generated for each branch of the if-else statement\index{if statement}.  For each variable \texttt{V} that occurs on the LHS of an assignment\index{assignment} statement that is inside of the if-else statement\index{if statement}, predicate \texttt{p} is passed two arguments, \texttt{Vin} and \texttt{Vout}.  In the above example, \texttt{X} and \texttt{Y} each occur on the LHS of an assignment\index{assignment} statement.  Therefore, predicate \texttt{p} is passed the parameters \texttt{Xin}, \texttt{Xout}, \texttt{Yin}, and \texttt{Yout}. 

\section{Types of Loops}
Picat has three types of loop statements for programming repetitions: \texttt{foreach}\index{foreach loop}, \texttt{while}\index{while loop}, and \texttt{do-while}\index{do-while loop}.

\subsection{Foreach Loops}
A \texttt{foreach} loop\index{foreach loop} has 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}
Each $E_i$ is an \emph{iterating pattern}\index{iterator}.  Each $D_i$ is an expression that gives a \emph{compound value}\index{compound value}.  Each $Cond_i$ is an optional \emph{condition} on iterators\index{iterator} $E_1$ through $E_i$. 

Foreach loops\index{foreach loop} can be used to iterate through compound values\index{compound value}, as in the following examples.

\subsection*{Example}
\begin{verbatim}
loop_ex1 =>
    L = [17, 3, 41, 25, 8, 1, 6, 40],
    foreach (E in L)
        println(E)
    end.

loop_ex2(Map) =>
    foreach ((Key = Value) in Map)
        writef("%w = %w\n", Key, Value)
    end.
\end{verbatim}

The \texttt{loop\_ex1} example iterates through a list.  The \texttt{loop\_ex2} example iterates through a map, where \texttt{Key = Value} is the iterating pattern\index{iterator}.

The \texttt{loop\_ex1} example can also be written, using a \emph{failure-driven loop}\index{failure-driven loop}, as follows.

\subsection*{Example}
\begin{verbatim}
loop_ex1 =>
    L = [17, 3, 41, 25, 8, 1, 6, 40],
    (    member(E, L),
         println(E),
         fail
    ;
         true
    ).
\end{verbatim}


Recall that the range $Start .. Step .. End$ stands for a list of numbers.  Ranges can be used as compound values\index{compound value} in iterators\index{iterator}.
\subsection*{Example}
\begin{verbatim}
loop_ex3 =>
    foreach (E in 1 .. 2 .. 9)
        println(E)
    end.
\end{verbatim}

Also recall that the function \texttt{zip($List_1$,$List_2$,$\ldots$,$List_n$)}\index{\texttt{zip}} returns a list of tuples. This function can be used to simultaneously iterate over multiple lists.

\subsection*{Example:}
\begin{verbatim}
loop_ex_parallel =>
    foreach (Pair in zip(1..2, [a,b]))
        println(Pair)
    end.
\end{verbatim}


\subsection{Foreach Loops with Multiple Iterators}
Each of the previous examples uses a single iterator\index{iterator}.  Foreach loops\index{foreach loop} can also contain multiple iterators\index{iterator}.
\subsection*{Example:}
\begin{verbatim}
loop_ex4 =>
    L = [2, 3, 5, 10],
    foreach (I in L, J in 1 .. 10, J mod I != 0)
        printf("%d is not a multiple of %d%n", J, I)
    end.
\end{verbatim}

If a foreach loop\index{foreach loop} has multiple iterators\index{iterator}, then it is compiled into a series of nested foreach loops\index{foreach loop}\index{nested loop} in which each nested loop\index{nested loop} has a single iterator\index{iterator}.  In other words, a foreach loop\index{foreach loop} with multiple iterators\index{iterator} executes its goal once for every possible combination of values in the iterators\index{iterator}.

The foreach loop\index{foreach loop} in \texttt{loop\_ex4} is the same as the nested loop\index{nested loop}:
\begin{verbatim}
loop_ex5 =>
    L = [2, 3, 5, 10],
    foreach (I in L)
        foreach (J in 1..10)
            if (J mod I != 0)
               printf("%d is not a multiple of %d%n", J, I)
            end
        end
    end.
\end{verbatim}

\subsection{Foreach Loops with the \texttt{break} Condition}
When the condition \texttt{break($Cond$)}\index{\texttt{break}} occurs to the right of an iterator in a \texttt{foreach} loop, it terminates the iterator if $Cond$ is true. Note that the loop body is not executed when $Cond$ is true. 

The foreach loop in \texttt{loop\_ex6} prints out the elements of the array \texttt{A}, stopping when it encounters a 0.
\begin{verbatim}
loop_ex6 =>
    A = {2, 3, 5, 0, 10, 4},
    foreach (I in 1..len(A),  break(A[I] == 0))
        println(A[I])
    end.
\end{verbatim}


\subsection{While Loops}
A \texttt{while} loop\index{while loop} has the form:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{while ($Cond$)} \\
\> \> $Goal$  \\
\>  \texttt{end}
\end{tabbing} 
As long as $Cond$ succeeds, the loop will repeatedly execute $Goal$.  
\subsection*{Example:}
\begin{verbatim}
loop_ex7 =>
    I = 1, 
    while (I <= 9)
        println(I),
        I := I + 2
    end.

loop_ex8 =>
    J = 6,
    while (J <= 5)
        println(J),
        J := J + 1
    end.

loop_ex9 =>
    E = read_int(),
    while (E mod 2 == 0; E mod 5 == 0)
        println(E),
        E := read_int()
    end.

loop_ex10 =>
    E = read_int(),
    while (E mod 2 == 0, E mod 5 == 0)
        println(E),
        E := read_int()
    end.
\end{verbatim}

The while loop\index{while loop} in \texttt{loop\_ex7} prints all of the odd numbers between $1$ and $9$.  It is similar to the foreach loop\index{foreach loop}
\begin{verbatim}
foreach (I in 1 .. 2 .. 9)
    println(I)
end.
\end{verbatim}

The while loop\index{while loop} in \texttt{loop\_ex8} never executes its goal.  \texttt{J} begins at $6$, so the condition \texttt{J <= 5} is never true, meaning that the body of the loop does not execute.

The while loop\index{while loop} in \texttt{loop\_ex9} demonstrates a compound condition.  The loop executes as long as the value that is read into \texttt{E} is either a multiple of $2$ or a multiple of $5$.

The while loop\index{while loop} in \texttt{loop\_ex10} also demonstrates a compound condition.  Unlike in \texttt{loop\_ex9}, in which either condition must be true, in \texttt{loop\_ex10}, both conditions must be true.  The loop executes as long as the value that is read into \texttt{E} is both a multiple of $2$ and a multiple of $5$. 

\subsection{Do-while Loops}
A \texttt{do-while} loop\index{do-while loop} has the form:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{do} \\
\> \> $Goal$  \\
\>  \texttt{while ($Cond$)}
\end{tabbing} 
A do-while loop\index{do-while loop} is similar to a while loop\index{while loop}, except that a do-while loop\index{do-while loop} executes $Goal$ one time before testing $Cond$.  The following example demonstrates the similarities and differences between do-while loops\index{do-while loop} and while loops\index{while loop}.
\subsection*{Example}
\begin{verbatim}
loop_ex11 =>
    J = 6,
    do
        println(J),
        J := J + 1
    while (J <= 5).
\end{verbatim}

Unlike \texttt{loop\_ex8}, \texttt{loop\_ex11} executes its body once.  Although \texttt{J} begins at $6$, the do-while loop\index{do-while loop} prints \texttt{J}, and increments \texttt{J} before evaluating the condition \texttt{J <= 5}.

\section{List and Array Comprehensions}
A \emph{list comprehension}\index{list comprehension} is a special functional notation for creating lists.  List comprehensions\index{list comprehension} have a similar format to foreach loops\index{foreach loop}.
\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}
$T$ is an expression.  Each $E_i$ is an \emph{iterating pattern}\index{iterator}.  Each $D_i$ is an expression that gives a \emph{compound value}\index{compound value}.  Each $Cond_i$ is an optional \emph{condition} on iterators\index{iterator} $E_1$ through $E_i$.

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}

\subsection*{Example}
\begin{verbatim}
picat> L = [(A, I) : A in [a, b], I in 1 .. 2].
L = [(a , 1),(a , 2),(b , 1),(b , 2)]

picat> L = {(A, I) : A in [a, b], I in 1 .. 2}.
L = {(a , 1),(a , 2),(b , 1),(b , 2)}
\end{verbatim}

\section{Compilation of Loops}
Variables that occur 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 rule
\begin{verbatim}
p(A) =>
    foreach (I in 1 .. A.length)
        E = A[I],
        println(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.

Consider the example:
\subsection*{Example}
\begin{verbatim}
while_test(N) =>
    I = 1,
    while (I <= N)
        I := I + 1,
        println(I)
    end.
\end{verbatim}
In this example, the while loop\index{while loop} contains an assignment\index{assignment} statement.  As mentioned above, at compilation time, Picat creates new variables in order to handle assignments\index{assignment}.  One new variable is created for each assignment\index{assignment}.  However, when this example is compiled, the compiler does not know the number of times that the body of the while loop\index{while loop} can be executed.  This means that the compiler does not know how many times the assignment\index{assignment} \texttt{I := I + 1} will occur, and the compiler is unable to create new variables for this assignment\index{assignment}.  In order to solve this problem, the compiler compiles while loops\index{while loop} into tail-recursive\index{tail recursion} predicates.

In the \texttt{while\_test} example, the while loop\index{while loop} is compiled into:
\begin{verbatim}
while_test(N) =>
    I = 1,
    p(I, N).

p(I, N), I <= N => 
    I1 = I + 1,
    println(I1),
    p(I1, N).
p(_, _) => true. 
\end{verbatim}

Note that the first rule of the predicate \texttt{p(I, N)} has the same condition as the while loop\index{while loop}.  The second rule, which has no condition, terminates the while loop\index{while loop}, because the second rule is only executed if \texttt{I > N}.  The call \texttt{p(I1, N)} is the tail-recursive\index{tail recursion} call, with \texttt{I1} storing the modified value.

Suppose that a while loop\index{while loop} modifies a variable that is then used outside of the while loop\index{while loop}.   For each modified variable \texttt{V} that is used after the while loop\index{while loop}, predicate \texttt{p} is passed two arguments, \texttt{Vin} and \texttt{Vout}.  Then, a predicate that has the body \texttt{true}\index{\texttt{true}} is not sufficient to terminate the compiled while loop\index{while loop}. 

The next example demonstrates a loop that has multiple accumulators\index{accumulator}, and that modifies values which are then used outside of the loop.
\subsection*{Example}
\begin{verbatim}
min_max([H|T], Min, Max) =>
    LMin = H,
    LMax = H,
    foreach (E in T)
        LMin := min(LMin, E),
        LMax := max(LMax, E)
    end,
    Min = LMin,
    Max = LMax.
\end{verbatim}

This loop finds the minimum and maximum values of a list.  The loop is compiled to:
\begin{verbatim}
min_max([H|T], Min, Max) =>
    LMin = H,
    LMax = H,
    p(T, LMin, LMin1, LMax, LMax1),
    Min = LMin1,
    Max = LMax1.

p([], MinIn, MinOut, MaxIn, MaxOut) =>
    MinOut = MinIn,
    MaxOut = MaxIn.
p([E|T], MinIn, MinOut, MaxIn, MaxOut) =>
    Min1 = min(MinIn, E),
    Max1 = max(MaxIn, E),
    p(T, Min1, MinOut, Max1, MaxOut).
\end{verbatim}
Notice that there are multiple accumulators\index{accumulator}: \texttt{MinIn} and \texttt{MaxIn}.  Since the \texttt{min\_max} predicate returns two values, the accumulators each have an \textit{in} variable (\texttt{MinIn} and \texttt{Maxin}) and an \textit{out} variable (\texttt{MinOut} and \texttt{MaxOut}).   If the first parameter of predicate \texttt{p} is an empty list, then \texttt{MinOut} is set to the value of \texttt{MinIn}, and \texttt{MaxOut} is set to the value of \texttt{MaxIn}.

Foreach\index{foreach loop} and do-while loops\index{do-while loop} are compiled in a similar manner to while loops\index{while loop}.

\subsubsection{Nested Loops}
As mentioned above, variables that only occur within a loop are local\index{local variable} to each iteration of the loop.  In nested loops\index{nested loop}, variables that are local\index{local variable} to the outer loop are global to the inner loop.  In other words, if a variable occurs in the outer loop, then the variable is also visible in the inner loop.  However, variables that are local\index{local variable} to the inner loop are not visiable to the outer loop.

For example, consider the nested loops\index{nested loop}:
\begin{verbatim}
nested =>
    foreach (I in 1 .. 10)
        printf("Numbers between %d and %d ", I, I * I),
        foreach (J in I .. I * I)
            printf("%d ", J)
        end,
        nl
    end.
\end{verbatim}
Variable \texttt{I} is local\index{local variable} to the outer foreach loop\index{foreach loop}, and is global to the inner foreach loop\index{foreach loop}.  Therefore, iterator\index{iterator} \texttt{J} is able to iterate from \texttt{I} to \texttt{I * I} in the inner foreach loop\index{foreach loop}.  Iterator\index{iterator} \texttt{J} is local\index{local variable} to the inner loop, and does not occur in the outer loop.

Since a foreach loop\index{foreach loop} with \texttt{N} iterators\index{iterator} is converted into \texttt{N} nested foreach loops\index{foreach loop}\index{nested loop}, the order of the iterators\index{iterator} matters.  

\subsection{List Comprehensions}
List comprehensions\index{list comprehension} are compiled into foreach loops\index{foreach loop}.

\subsection*{Example}
\begin{verbatim}
comp_ex =>
    L = [(A, X) : A in [a, b], X in 1 .. 2].
\end{verbatim}
This list comprehension\index{list comprehension} is compiled to:
\begin{verbatim}
comp_ex =>
    List = L, 
    foreach (A in [a, b], X in 1 .. 2)
        L = [(A, X) | T], 
        L := T
    end,
    L = [].
\end{verbatim}

\subsection*{Example}
\begin{verbatim}
make_list1 =>
    L = [Y : X in 1..5],
    write(L).

make_list2 =>
    Y = Y,
    L = [Y : X in 1..5],
    write(L).
\end{verbatim}
Suppose that a user would like to create a list \texttt{[Y, Y, Y, Y, Y]}.  The \texttt{make\_list1} predicate incorrectly attempts to make this list; instead, it outputs a list of 5 different variables since \texttt{Y} is local.  In order to make all five variables the same, \texttt{make\_list2} makes variable \texttt{Y} global, by adding the line \texttt{Y = Y} to globalize \texttt{Y}.

\ignore{
\end{document}
}
\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:exception}Exceptions}
An \emph{exception}\index{exception} is an event that occurs during the execution of a program.  An exception\index{exception} requires a special treatment. In Picat, an exception\index{exception} is just a term. A built-in exception\index{exception} is a structure\index{structure}, where the name denotes the \emph{type} of the exception\index{exception}, and the arguments provide other information about the exception\index{exception}, such as the \emph{source}, which is the goal or function that raised the exception\index{exception}.

\section{Built-in Exceptions}
Picat throws many types of exceptions. The following are some of the built-in exceptions\index{exception}:\footnote{In the current implementation, exceptions thrown by B-Prolog are not compliant with the documentation.}
\begin{itemize}
\item \texttt{zero\_divisor($Source$)}: $Source$ divides a number by zero.
\item \texttt{domain\_error($Val$,$Source$)}: $Source$ receives a value $Val$ that is unexpected in the domain.
\item \texttt{existence\_error($Entity$,$Source$)}: $Source$ tries to use $Entity$, such as a file, a function, or a solver, that does not exist.
% \item \texttt{function\_not\_found($FName$,$Source$)}: $Source$ tries to call a function that is not defined in the imported modules, where $Source$ is a higher-order call in which names cannot be completely bound to definitions at compile time.
\item \texttt{interrupt($Source$)}: The execution is interrupted\index{interrupt} by a signal. For an interrupt\index{interrupt} caused by \texttt{ctrl-c}, $Source$ is \texttt{keyboard}.
\item \texttt{io\_error($ENo$,$EMsg$,$Source$)}: An I/O error with the number $ENo$ and message $EMsg$ occurs in $Source$.
%\item \texttt{key\_not\_found($Key$,$Source$)}: $Source$ tries to access a map or an attributed variable with a $Key$ that does not exist.
\item \texttt{load\_error($FName$,$Source$)}: An error occurs while loading the byte-code file named $FName$.  This error is caused by the malformatted byte-code file.
\item \texttt{out\_of\_memory($Area$)}: The system runs out of memory while expanding $Area$, which can be: \texttt{stack\_heap}, \texttt{trail}, \texttt{program}, \texttt{table}, or \texttt{findall}.
\item \texttt{out\_of\_bound($EIndex$,$Source$)}: $Source$ tries to access an element of a compound value using the index $EIndex$, which is out of bound.  An index is out of bound if it is less than or equal to zero, or if it is greater than the length of the compound value.
%\item \texttt{predicate\_not\_found($PredName$,$Source$)}: $Source$ tries to call a predicate that is not defined in the imported modules, where $Source$ is a higher-order call in which names cannot be completely bound to definitions at compile time.
\item \texttt{syntax\_error($String$,$Source$)}: $String$ cannot be parsed into a value that is expected by $Source$. For example, \texttt{read\_int()}\index{\texttt{read\_int/0}} throws this exception\index{exception} if it reads in a string \texttt{"a"} rather than an integer.
\item \texttt{unresolved\_function\_call($FCall$)}: No rule is applicable to the function call $FCall$.
\item \texttt{\emph{Type}\_expected($EArg$,$Source$)}: The argument $EArg$ in $Source$ is not an expected type or value, where $Type$ can be \texttt{var}, \texttt{nonvar}, \texttt{dvar}, \texttt{atom}, \texttt{integer}, \texttt{real}, \texttt{number}, \texttt{list}, \texttt{map}, etc.
\end{itemize}

\section{Throwing Exceptions}
The built-in predicate \texttt{throw($Exception$)}\index{\texttt{throw/1}}  throws $Exception$. After an exception\index{exception} is thrown, the system searches for a handler\index{handler} for the exception\index{exception}. If none is found, then the system displays the exception\index{exception} and aborts the execution of the current query. It also prints the backtrace of the stack if it is in debug mode. For example, for the function call \texttt{open("abc.txt")}\index{\texttt{open/1}}, the following message will be displayed if there is no file that is named \texttt{"abc.txt"}.
\begin{verbatim}
    *** error(existence_error(source_sink,abc.txt),open)
\end{verbatim}

\section{Defining Exception Handlers}
All exceptions, including those raised by built-ins and interruptions, can be caught by catchers. A catcher is a call in the form:
\begin{verbatim}
      catch(Goal,Exception,RecoverGoal)
\end{verbatim}
which is equivalent to \texttt{Goal}, except when an exception is raised during the execution of \texttt{Goal} that unifies \texttt{Exception}. When such an exception is raised, all of the bindings that have been performed on variables in \texttt{Goal} will be undone, and \texttt{RecoverGoal} will be executed to handle the exception. Note that \texttt{Exception} is unified with a renamed copy of the exception before \texttt{RecoverGoal} is executed. Also note that only exceptions that are raised by a descendant call of \texttt{Goal} can be caught.
\index{\texttt{catch/3}}

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

\ignore{
The \texttt{try}\index{\texttt{try}} statement, which takes the following form, is provided for defining exception\index{exception} handlers\index{handler}:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{try} \\
\> \> $Goal$  \\
\>  \texttt{catch ($Pattern_1$)} \\
\> \>  \texttt{$Handler_1$} \\
\> $\vdots$ \\
\>  \texttt{catch ($Pattern_n$)} \\
\> \>  \texttt{$Handler_n$} \\
\>  \texttt{finally} \\
\> \>  \texttt{$Handler_{fin}$} \\
\> \texttt{end} 
\end{tabbing}
The \texttt{catch}\index{\texttt{catch}} clauses and the \texttt{finally}\index{\texttt{finally}} clause are optional.  However, the \texttt{finally}\index{\texttt{finally}} clause is mandated if there is no \texttt{catch}\index{\texttt{catch}} clause, and there must be at least one \texttt{catch}\index{\texttt{catch}} clause if there is no \texttt{finally}\index{\texttt{finally}} clause. Each $Pattern_i$ is a term pattern, like the head of a rule, and each handler\index{handler} is a goal. For an exception\index{exception}, a \texttt{catch}\index{\texttt{catch}} clause is said to be \emph{applicable} if the exception\index{exception} matches the pattern of the clause. When an exception\index{exception} is thrown during the execution of $Goal$, Picat walks along the chain of ancestor calls of the thrower of the exception\index{exception} until it finds an ancestor that is wrapped inside a \texttt{try}\index{\texttt{try}} statement. For the \texttt{try}\index{\texttt{try}} statement, Picat searches for the first applicable \texttt{catch}\index{\texttt{catch}} clause and executes the handler\index{handler}. If no \texttt{catch}\index{\texttt{catch}} clause exists, or no \texttt{catch}\index{\texttt{catch}} clause is applicable to the exception\index{exception}, then $Handler_{fin}$ is executed before the exception\index{exception} is re-thrown. The \texttt{finally}\index{\texttt{finally}} clause is always executed, if it exists.  It is executed when $Goal$ terminates with an exception\index{exception}, and it is executed when $Goal$ finishes its normal execution.  This means that the \texttt{finally}\index{\texttt{finally}} clause is executed when $Goal$ succeeds deterministically with no choice points left behind, and when $Goal$ fails.  For example,
\begin{verbatim}
    try
        S = open(File),
        process(S)
    catch (E)
        writeln(E)
    finally
        close(S).
\end{verbatim}
The \texttt{finally}\index{\texttt{finally}} clause specifies a clean-up action for the \texttt{try}\index{\texttt{try}} goal.
}
\ignore{
\end{document}
}
\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:tabling}Tabling}
The Picat system is a term-rewriting system. For a predicate call, Picat selects a matching rule and rewrites the call into the body of the rule. For a function call $C$, Picat rewrites the equation $C = X$ where $X$ is a variable that holds the return value of $C$. Due to the existence of recursion in programs, the term-rewriting process may never terminate. Consider, for example, the following program:  
\begin{verbatim}
    reach(X,Y) ?=> edge(X,Y).
    reach(X,Y) => reach(X,Z), edge(Z,Y).
\end{verbatim}
where the predicate \texttt{edge} defines a relation, and the predicate \texttt{reach} defines the transitive closure of the relation. For a query such as \texttt{reach(a,X)}, the program never terminates due to the existence of left-recursion in the second rule. Even if the rule is converted to right-recursion, the query may still not terminate if the graph that is represented by the relation contains cycles. 

Another issue with recursion is redundancy. Consider the following problem: \emph{Starting in the top left corner of a $N\times N$ grid, one can either go rightward or downward. How many routes are there through the grid to the bottom right corner?} The following gives a program in Picat for the problem:
\begin{verbatim}
    route(N,N,_Col) = 1.
    route(N,_Row,N) = 1.
    route(N,Row,Col) = route(N,Row+1,Col)+route(N,Row,Col+1).
\end{verbatim}
The function call \texttt{route(20,1,1)} returns the number of routes through a 20$\times$20 grid. The function call \texttt{route(N,1,1)} takes exponential time in \texttt{N}, because the same function calls are repeatedly spawned during the execution, and are repeatedly resolved each time that they are spawned.

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

\subsection*{Example}
\begin{verbatim}
    table
    reach(X,Y) ?=> edge(X,Y).
    reach(X,Y) => reach(X,Z), edge(Z,Y).

    table
    route(N,N,_Col) = 1.
    route(N,_Row,N) = 1.
    route(N,Row,Col) = route(N,Row+1,Col)+route(N,Row,Col+1).
\end{verbatim}
With tabling\index{tabling}, all queries to the \texttt{reach} predicate are guaranteed to terminate, and the function call \texttt{route(N,1,1)} takes only \texttt{N}$^2$ time.

For some problems, such as planning problems, it is infeasible to table\index{tabling} all answers, because there may be an infinite number of answers. For some other problems, such as those that require the computation of aggregates, it is a waste to table\index{tabling} non-contributing answers. Picat allows users to provide table modes\index{mode-directed tabling} to instruct the system about which answers to table\index{tabling}. For a tabled\index{tabling} predicate, users can give a \emph{table mode declaration}\index{mode-directed tabling} in the form ($M_{1},M_{2},\ldots,M_{n}$), where each $M_{i}$ is one of the following: 
\begin{itemize}
\item + : indicates input
\item - : indicates output
\item \texttt{max}: indicates that the corresponding variable should be maximized (only the first best answer is tabled).\index{\texttt{max}}
\item \texttt{min} indicates that the corresponding variable should be minimized (only the first best answer is tabled).\index{\texttt{min}}
\item \texttt{mmax}: indicates that the corresponding variable should be maximized (all best answers are tabled).\index{\texttt{mmax}}
\item \texttt{mmin} indicates that the corresponding variable should be minimized (all best answers are tabled).\index{\texttt{mmin}}
\end{itemize}
The last mode $M_{n}$ can be \texttt{nt}, which indicates that the argument is not tabled. Two types of data can be passed to a tabled predicate as an \texttt{nt} argument: (1) global data that are the same to all the calls of the predicate, and (2) data that are functionally dependent on the input arguments.

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

\subsection*{Example}
\begin{verbatim}
    table(+,+,-,min)
    sp(X,Y,Path,W) ?=>
        Path = [(X,Y)],
        edge(X,Y,W).
    sp(X,Y,Path,W) =>
        Path = [(X,Z)|Path1],
        edge(X,Z,Wxz),
        sp(Z,Y,Path1,W1),
        W = Wxz+W1.
\end{verbatim}
The predicate \texttt{edge(X,Y,W)} specifies a weighted directed graph, where \texttt{W} is the weight of the edge between node \texttt{X} and node \texttt{Y}. The predicate \texttt{sp(X,Y,Path,W)} states that \texttt{Path} is a path from \texttt{X} to \texttt{Y} with the minimum weight \texttt{W}. Note that whenever the predicate \texttt{ sp/4} is called, the first two arguments must always be instantiated. For each pair, the system stores only one path with the minimum weight. When the mode \texttt{min} is replaced with \texttt{mmin}, the system stores all paths with the minimum weight.

The following program finds a shortest path among those with the minimum weight for each pair of nodes:
\begin{verbatim}
    table (+,+,-,min).
    sp(X,Y,Path,WL) ?=>
        Path = [(X,Y)],
        WL = (Wxy,1),
        edge(X,Y,Wxy).
    sp(X,Y,Path,WL) =>
        Path = [(X,Z)|Path1],
        edge(X,Z,Wxz),
        sp(Z,Y,Path1,WL1),
        WL1 = (Wzy,Len1),
        WL = (Wxz+Wzy,Len1+1).
\end{verbatim}
For each pair of nodes, the pair of variables \texttt{(W,Len)} is minimized, where \texttt{W} is the weight, and \texttt{Len} is the length of a path. The built-in function \texttt{compare\_terms($T_1$,$T_2$)} is used to compare answers. Note that the order is important. If the term would be \texttt{(Len,W)}, then the program would find a shortest path, breaking a tie by selecting one with the minimum weight.

The tabling system is useful for offering dynamic programming solutions for planning problems. The following shows a tabled program for general planning problems:
\begin{verbatim}
    table (+,-,min)
    plan(S,Plan,Len), final(S) => Plan = [], Len = 0.
    plan(S,Plan,Len) =>
        action(Action,S,S1),
        plan(S1,Plan1,Len1),
        Plan = [Action|Plan1],
        Len = Len1+1.
\end{verbatim}
The predicate \texttt{action(Action,S,S1)} selects an action and performs the action on state \texttt{S} to generate another state, \texttt{S1}. Again, by replacing \texttt{min} with \texttt{mmin}, the predicate \texttt{plan} can be employed to generate all optimal plans.

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


\begin{figure}
\begin{center}
\begin{verbatim}
    go =>
        S0 = [s,s,s,s],
        plan(S0,Plan,_),
        writeln(Plan.reverse()).

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

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

    unsafe([F,W,G,_C]), W == G, F !== W => true.
    unsafe([F,_W,G,C]), G == C, F !== G => true.
\end{verbatim}
\end{center}
\caption{\label{fig:farmer}A program for the Farmer's problem.}
\end{figure}

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

\begin{itemize}
\item \texttt{initialize\_table}\index{\texttt{initialize\_table/0}}: This predicate initializes the table area.   
\end{itemize}
This predicate clears up the table area. It's the user's responsibility to ensure that no data in the table area are referenced by any part of the application.

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

\begin{description}
\item[Subgoal lookup and registration:] This operation is used when a tabled\index{tabling} subgoal is encountered during execution. It looks up the subgoal table\index{tabling} to see if there is a variant of the subgoal. If not, it inserts the subgoal (termed a \emph{pioneer} or \emph{generator}) into the subgoal table\index{tabling}. It also allocates an answer table\index{tabling} for the subgoal and its variants. Initially, the answer table\index{tabling} is empty. If the lookup finds that there already is a variant of the subgoal in the table\index{tabling}, then the record that is stored in the table\index{tabling} is used for the subgoal (called a \emph{consumer}). Generators and consumers are handled differently. In linear tabling\index{linear tabling}, a generator is resolved using rules, and a consumer is resolved using answers; a generator is iterated until the fixed point is reached, and a consumer fails after it exhausts all of the existing answers.
\item[Answer lookup and registration:] This operation is executed when a rule succeeds in generating an answer for a tabled\index{tabling} subgoal. If a variant of the answer already exists in the table\index{tabling}, then it does nothing; otherwise, it inserts the answer into the answer table\index{tabling} for the subgoal, or it tables\index{tabling} the answer according to the mode declaration. Picat uses the lazy consumption strategy (also called the local strategy). After an answer is processed, the system backtracks to produce the next answer. 
\item[Answer return:] When a consumer is encountered, an answer is returned immediately, if an answer exists. On backtracking, the next answer is returned. A generator starts consuming its answers after it has exhausted all of its rules. Under the lazy consumption strategy, a top-most looping generator does not return any answer until it is complete.
\end{description}

\ignore{
\section{Initialization of the Table Area}
\begin{itemize}
\item \texttt{table\_get\_all($Goal$) = $List$}\index{\texttt{table\_get\_all/1}}:  This function returns a list of answers of the subgoals that are subsumed by $Goal$. For example, the \texttt{table\_get\_all(\_)}\index{\texttt{table\_get\_all/1}} fetches all of the answers in the table\index{tabling}, since any subgoal is subsumed by the anonymous variable\index{anonymous variable}.
\item \texttt{table\_get\_one($Goal$)}\index{\texttt{table\_get\_one/1}}: If there is a subgoal in the subgoal table\index{tabling} that is a variant of \texttt{$Goal$}, and that has answers, then \texttt{$Goal$} is unified with the first answer. This predicate fails if there is no variant subgoal in the table\index{tabling}, or if there is no answer available.
\end{itemize}
}

\ignore{
\end{document}
}
\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:planner}The \texttt{planner} Module}
The \texttt{planner} module provides several predicates for solving planning problems. Given an initial state, a final state, and a set of possible actions, a planning problem is to find a plan that transforms the initial state to the final state. In order to use the \texttt{planner} module to solve a planning problem, users have to provide the condition for the final states and the state transition diagram through the following global predicates:\index{planning}\index{planner}
\begin{itemize}
\item \texttt{final($S$)}\index{\texttt{final/1}}: This predicate succeeds if $S$ is a final state.
\item \texttt{final($S$,$Plan$,$Cost$)}\index{\texttt{final/3}}: A final state can be reached from $S$ by the action sequence in $Plan$ with $Cost$. If this predicate is not given, then the system assumes the following definition:
\begin{verbatim}
    final(S,Plan,Cost) => Plan = [], Cost = 0, final(S).
\end{verbatim}

\item \texttt{action($S$,$NextS$,$Action$,$ActionCost$)}\index{\texttt{action/4}}: This predicate encodes the state transition diagram of the planning problem. The state $S$ can be transformed into $NextS$ by performing $Action$. The cost of $Action$ is $ActionCost$. If the plan's length is the only interest, then $ActionCost$ should be 1.
\end{itemize}

A state is normally a ground term. As all states are tabled during search, it is of paramount importance to find a good representation for states such that terms among states can be shared as much as possible.

In addition to the two required predicates given above, users can optionally provide the following global procedures to assist Picat in searching for plans:
\begin{itemize}
\item \texttt{heuristic($S$)}\index{\texttt{heuristic/1}}: This function returns an estimation of the resource amount needed to transform $S$ into a goal state. This estimation is said to be \textit{admissible} if it never exceeds the real cost. All heuristic estimations must be admissible in order for the planner to find optimal plans. This function is used by the planner to check the heuristic estimation before each state expansion.

\item \texttt{sequence($P$,$Action$)}\index{\texttt{sequence/2}}: This predicate binds $Action$ to a viable action form based on the current partial plan $P$. Note that the actions in list $P$ are in reversed order, with the most recent action occurring first in the list, and the first action occurring last in the list. The planner calls \texttt{sequence/2} to find an action for expanding the current state before calling \texttt{action/4}. For example,
\begin{verbatim}
sequence([move(R,X,Y)|_], Action) ?=> Action = $move(R,Y,_).
sequence([move(R,_,_)|_], Action) ?=> Action = $jump(R).
sequence([move(R,_,_)|_], Action) => Action = $wait(R).
sequence(_, _) => true.
\end{verbatim}
These sequence rules ban robots from moving in an interleaving fashion; a robot must continue to move until it takes the action \texttt{jump} or \texttt{wait} before another robot can start moving. The last rule \texttt{sequence(\_, \_) => true} is necessary; it permits any action to be taken if the partial plan is empty, or if the most recent action in the partial plan is not \texttt{move}.
\end{itemize}

\section{Depth-Bounded Search}
Depth-bounded search amounts to exploring the search space, taking into account the current available resource amount. A new state is only explored if the available resource amount is non-negative. When depth-bounded search is used, the function {\tt current\_resource()} can be used to retrieve the current resource amount. If the heuristic estimate of the cost to travel from the current state to the final state is greater than the available resource amount, then the current state fails.

\begin{itemize}
\item \texttt{plan($S$,$Limit$,$Plan$,$Cost$)}\index{\texttt{plan/4}}: This predicate, if it succeeds, binds $Plan$ to a plan that can transform state $S$ to a final state that satisfies the condition given by {\tt final/1} or {\tt final/3}. $Cost$ is the cost of $Plan$, which cannot exceed $Limit$, which is a given non-negative integer. 

\item \texttt{plan($S$,$Limit$,$Plan$)}: If the second argument is an integer, then this predicate is the same as the \texttt{plan/4} predicate, except that the plan's cost is not returned. 

\item \texttt{plan($S$,$Plan$,$Cost$)}:\index{\texttt{plan/3}} If the second argument is a variable, then this predicate is the same as the \texttt{plan/4} predicate, except that the limit is assumed to be 268435455.

\item \texttt{plan($S$,$Plan$)}\index{\texttt{plan/2}}: This predicate is the same as the \texttt{plan/4} predicate, except that the limit is assumed to be 268435455, and that the plan's cost is not returned.

\item \texttt{best\_plan($S$,$Limit$,$Plan$,$Cost$)}\index{\texttt{best\_plan/4}}: This predicate finds an optimal plan by using the following algorithm:  It first calls {\tt plan/4} to find a plan of 0 cost. If no plan is found, then it increases the cost limit to 1 or double the cost limit. Once a plan is found, the algorithm uses binary search to find an optimal plan.

\item \texttt{best\_plan($S$,$Limit$,$Plan$)}: If the second argument is an integer, then this predicate is the same as the \texttt{best\_plan/4} predicate, except that the plan's cost is not returned. 

\item \texttt{best\_plan($S$,$Plan$,$Cost$)}\index{\texttt{best\_plan/3}}: If the second argument is a variable, then this predicate is the same as the \texttt{best\_plan/4} predicate, except that the limit is assumed to be 268435455.

\item \texttt{best\_plan($S$,$Plan$)}\index{\texttt{best\_plan/2}}: This predicate is the same as the \texttt{best\_plan/4} predicate, except that the limit is assumed to be 268435455, and that the plan's cost is not returned.

\item \texttt{best\_plan\_bb($S$,$Limit$,$Plan$,$Cost$)}\index{\texttt{best\_plan\_bb/4}}: 
This predicate, if it succeeds, binds $Plan$ to an optimal plan that can transform state $S$ to a final state. $Cost$ is the cost of $Plan$, which cannot exceed $Limit$, which is a given non-negative integer. The branch-and-bound algorithm is used to find an optimal plan.

\item \texttt{best\_plan\_bb($S$,$Limit$,$Plan$)}: If the second argument is an integer, then this predicate is the same as the \texttt{best\_plan\_bb/4} predicate, except that the plan's cost is not returned. 

\item \texttt{best\_plan\_bb($S$,$Plan$,$Cost$)}\index{\texttt{best\_plan\_bb/3}}: If the second argument is a variable, then this predicate is the same as the \texttt{best\_plan\_bb/4} predicate, except that the limit is assumed to be 268435455.

\item \texttt{best\_plan\_bb($S$,$Plan$)}\index{\texttt{best\_plan\_bb/2}}: 
This predicate is the same as the \texttt{best\_plan\_bb/4} predicate, except that the limit is assumed to be 268435455, and that the plan's cost is not returned.

\item \texttt{best\_plan\_bin($S$,$Limit$,$Plan$,$Cost$)}\index{\texttt{best\_plan\_bin/4}}: 
This predicate, if it succeeds, binds $Plan$ to an optimal plan that can transform state $S$ to a final state. $Cost$ is the cost of $Plan$, which cannot exceed $Limit$, which is a given non-negative integer. The branch-and-bound algorithm is used with binary search to find an optimal plan.

\item \texttt{best\_plan\_bin($S$,$Limit$,$Plan$)}: If the second argument is an integer, then this predicate is the same as the \texttt{best\_plan\_bin/4} predicate, except that the plan's cost is not returned. 

\item \texttt{best\_plan\_bin($S$,$Plan$,$Cost$)}\index{\texttt{best\_plan\_bin/3}}: If the second argument is a variable, then this predicate is the same as the \texttt{best\_plan\_bin/4} predicate, except that the limit is assumed to be 268435455.

\item \texttt{best\_plan\_bin($S$,$Plan$)}\index{\texttt{best\_plan\_bin/2}}: 
This predicate is the same as the \texttt{best\_plan\_bin/4} predicate, except that the limit is assumed to be 268435455, and that the plan's cost is not returned.

\item \texttt{current\_resource()=$Amount$}\index{\texttt{current\_resource/0}}: This function returns the current available resource amount of the current node. If the current execution path was not initiated by one of the calls that performs resource-bounded search, then 268435455 is returned. This function can be used to check the heuristics. If the heuristic estimate of the cost to travel from the current state to a final state is greater than the available resource amount, then the current state can be failed.

\item \texttt{current\_plan()=$Plan$}\index{\texttt{current\_plan/0}}: This function returns the current plan that has transformed the initial state to the current state. If the current execution path was not initiated by one of the calls that performs resource-bounded search, then [] is returned.

\item \texttt{current\_resource\_plan\_cost($Amount$,$Plan$,$Cost$)}\index{\texttt{current\_resource\_plan\_cost/3}}: This predicate retrieves the attributes of the current node in the search tree, including the resource amount, the path to the node, and its cost.

\item \texttt{is\_tabled\_state($S$)}\index{\texttt{is\_tabled\_state/1}}: This predicate succeeds if the state $S$ has been explored before and has been tabled.
\end{itemize}

\section{Depth-Unbounded Search}
In contrast to depth-bounded search, depth-unbounded search does not take into account the available resource amount. A new state can be explored even if no resource is available for the exploration. The advantage of depth-unbounded search is that failed states are never re-explored.

\begin{itemize}
\item \texttt{best\_plan\_nondet($S$,$Limit$,$Plan$,$Cost$)}\index{\texttt{best\_plan\_nondet/4}}: This predicate is the same as \\\texttt{best\_plan($S$,$Limit$,$Plan$,$Cost$)}, except that it allows multiple best plans to be returned through backtracking.

\item \texttt{best\_plan\_nondet($S$,$Limit$,$Plan$)}: If the second argument is an integer, then this predicate is the same as the \texttt{best\_plan\_nondet/4} predicate, except that the plan's cost is not returned. 

\item \texttt{best\_plan\_nondet($S$,$Plan$,$Cost$)}\index{\texttt{best\_plan\_nondet/3}}: If the second argument is a variable, then this predicate is the same as the \texttt{best\_plan\_nondet/4} predicate, except that the limit is assumed to be 268435455.

\item \texttt{best\_plan\_nondet($S$,$Plan$)}\index{\texttt{best\_plan\_nondet/2}}: This predicate is the same as the \texttt{best\_plan\_nondet/4} predicate, except that the limit is assumed to be 268435455, and that the plan's cost is not returned.

\item \texttt{plan\_unbounded($S$,$Limit$,$Plan$,$Cost$)}\index{\texttt{plan\_unbounded/4}}: This predicate, if it succeeds, binds $Plan$ to a plan that can transform state $S$ to a final state. $Cost$ is the cost of $Plan$, which cannot exceed $Limit$, which is a given non-negative integer.

\item \texttt{plan\_unbounded($S$,$Limit$,$Plan$)} If the second argument is an integer, then this predicate is the same as the \texttt{plan\_unbounded/4} predicate, except that the plan's cost is not returned. 

\item \texttt{plan\_unbounded($S$,$Plan$,$Cost$)}\index{\texttt{plan\_unbounded/3}}: If the second argument is a variable, then this predicate is the same as the \texttt{plan\_unbounded/4} predicate, except that the limit is assumed to be 268435455.

\item \texttt{plan\_unbounded($S$,$Plan$)}\index{\texttt{plan\_unbounded/2}}: This predicate is the same as the above predicate, except that the limit is assumed to be 268435455.

\item \texttt{best\_plan\_unbounded($S$,$Limit$,$Plan$,$Cost$)}\index{\texttt{best\_plan\_unbounded/4}}: This predicate, if it succeeds, binds $Plan$ to an optimal plan that can transform state $S$ to a final state. $Cost$ is the cost of $Plan$, which cannot exceed $Limit$, which is a given non-negative integer.

\item \texttt{best\_plan\_unbounded($S$,$Limit$,$Plan$)} If the second argument is an integer, then this predicate is the same as the \texttt{best\_plan\_unbounded/4} predicate, except that the plan's cost is not returned.

\item \texttt{best\_plan\_unbounded($S$,$Plan$,$Cost$)}\index{\texttt{best\_plan\_unbounded/3}}: If the second argument is a variable, then this predicate is the same as the \texttt{best\_plan\_unbounded/4} predicate, except that the limit is assumed to be 268435455.

\item \texttt{best\_plan\_unbounded($S$,$Plan$)}\index{\texttt{best\_plan\_unbounded/2}}: This predicate is the same as the above predicate, except that the limit is assumed to be 268435455.
\end{itemize}

\section{Examples}
The program shown in Figure \ref{fig:farmer2} solves the Farmer's problem by using the \texttt{planner} module. 

\begin{figure}
\begin{center}
\begin{verbatim}
    import planner.

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

    final([n,n,n,n]) => true.

    action([F,F,G,C],S1,Action,ActionCost) ?=>
        Action = farmer_wolf,
        ActionCost = 1,        
        opposite(F,F1),
        S1 = [F1,F1,G,C],
        not unsafe(S1).
    action([F,W,F,C],S1,Action,ActionCost) ?=>
        Action = farmer_goat,
        ActionCost = 1,        
        opposite(F,F1),
        S1 = [F1,W,F1,C],
        not unsafe(S1).
    action([F,W,G,F],S1,Action,ActionCost) ?=>
        Action = farmer_cabbage,
        ActionCost = 1,        
        opposite(F,F1),
        S1 = [F1,W,G,F1],
        not unsafe(S1).
    action([F,W,G,C],S1,Action,ActionCost) =>
        Action = farmer_alone,
        ActionCost = 1,        
        opposite(F,F1),
        S1 = [F1,W,G,C],
        not unsafe(S1).

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

    unsafe([F,W,G,_C]), W == G, F !== W => true.
    unsafe([F,_W,G,C]), G == C, F !== G => true.
\end{verbatim}
\end{center}
\caption{\label{fig:farmer2}A program for the Farmer's problem using \texttt{planner}.}
\end{figure}

Figure \ref{fig:15puzzlesol} gives a program for the 15-puzzle problem. A state is represented as a list of sixteen locations, each of which takes the form \texttt{($R_i$,$C_i$)}, where $R_i$ is a row number and $C_i$ is a column number. The first element in the list gives the position of the empty square, and the remaining elements in the list give the positions of the numbered tiles from 1 to 15. The function \texttt{heuristic(Tiles)} returns the Manhattan distance between the current state and the final state.

\begin{figure}[t]
\begin{center}
\begin{verbatim}
import planner.

main =>
    InitS = [(1,2),(2,2),(4,4),(1,3),
             (1,1),(3,2),(1,4),(2,4),
             (4,2),(3,1),(3,3),(2,3),
             (2,1),(4,1),(4,3),(3,4)],
    best_plan(InitS,Plan),
    foreach (Action in Plan)
       println(Action)
    end.

final(State) => State = [(1,1),(1,2),(1,3),(1,4),
                         (2,1),(2,2),(2,3),(2,4),
                         (3,1),(3,2),(3,3),(3,4),
                         (4,1),(4,2),(4,3),(4,4)].

action([P0@(R0,C0)|Tiles],NextS,Action,Cost) =>
    Cost = 1,
    (R1 = R0-1, R1 >= 1, C1 = C0, Action = up;
     R1 = R0+1, R1 =< 4, C1 = C0, Action = down;
     R1 = R0, C1 = C0-1, C1 >= 1, Action = left;
     R1 = R0, C1 = C0+1, C1 =< 4, Action = right),
    P1 = (R1,C1),
    slide(P0,P1,Tiles,NTiles),
    NextS = [P1|NTiles].

% slide the tile at P1 to the empty square at P0
slide(P0,P1,[P1|Tiles],NTiles) =>
    NTiles = [P0|Tiles].
slide(P0,P1,[Tile|Tiles],NTiles) =>
    NTiles = [Tile|NTilesR],
    slide(P0,P1,Tiles,NTilesR).

heuristic([_|Tiles]) = Dist =>
    final([_|FTiles]),
    Dist = sum([abs(R-FR)+abs(C-FC) : 
                {(R,C),(FR,FC)} in zip(Tiles,FTiles)]).
\end{verbatim}
\end{center}
\caption{\label{fig:15puzzlesol}A program for the 15-puzzle}
\end{figure}



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

\makeindex
\begin{document}
}
\chapter{Modules}
A module is a bundle of predicate and function definitions that are stored in one file. A module forms a name space.  Two definitions can have the same name if they reside in different modules. Because modules avoid name clashes, they are very useful for managing source files of large programs.

\section{Module and Import Declarations}
In Picat, source files must have the extension name \texttt{".pi"}.  A module is a source file that begins with a module name declaration in 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\index{file name}. A file that does not begin with a module declaration is assumed to belong to the default \emph{global} module\index{global module}. The following names are reserved for system modules and should not be used to name user modules: \texttt{basic}, \texttt{bp}, \texttt{cp}, \texttt{datetime}, \texttt{glb},  \texttt{io}, \texttt{math}, \texttt{mip}, \texttt{nn}, \texttt{ordset}, \texttt{os}, \texttt{planner}, \texttt{sat}, \texttt{smt}, \texttt{sys},  and \texttt{util}.

In order to use symbols that are defined in another module, users must explicitly import them with an import declaration in 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 imported $Name_i$ is a module name. For each imported module, the compiler first searches for it in the search path that is specified by the environment variable PICATPATH. If no module is found, the compiler gives an error message. Several modules are imported by default, including  \texttt{basic}, \texttt{io}, \texttt{math},  and \texttt{sys}.

The import relation is not transitive. Suppose that there are three modules: $A$, $B$, and $C$. If $A$ imports $B$ and $B$ imports $C$, then $A$ still needs to import $C$ in order to reference $C$'s symbols.

The built-in command \texttt{cl("xxx")}\index{\texttt{cl/1}} compiles the file \texttt{xxx.pi} and loads the generated code into the interpreter. The built-in command \texttt{load("xxx")} loads the bytecode file \texttt{xxx.qi}. It compiles the source file \texttt{xxx.pi} only when necessary. The \texttt{load}\index{\texttt{load/1}} command  also imports the public symbols defined in the module to the interpreter.  This allows users to use these symbols on the command line without explicitly importing the symbols. If the file \texttt{xxx.pi} imports modules, those module files will be compiled and loaded when necessary. 

A program file can contain \texttt{include} directives of the form:\index{\texttt{include} directive}
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{include $Name$}.
\end{tabbing}
where $Name$ is a string indicating a file name relative to the program file. The \texttt{include} directive causes the content of the file named $Name$ to be copied verbatim to where the directive occurs. The \texttt{include} directive allows users to split a large program into several source files. Note that the included source files cannot contain module or import declarations, and no definitions can span multiple files.

\section{Binding Calls to Definitions}
The Picat system has a global symbol table\index{symbol table} for atoms, a global symbol table\index{symbol table} for structure names, and a global symbol table\index{symbol table} for modules. For each module, Picat maintains a symbol table\index{symbol table} for the public predicate and function symbols defined in the module. Private symbols that are defined in a module are compiled away, and are never stored in the symbol table\index{symbol table}. While predicate and function symbols can be local to a module, atoms and structures are always global.

The Picat module system is static, meaning that the binding of normal (or non-higher-order) calls to their definitions takes place at compile time. For each call, the compiler first searches the default modules for a definition that has the same name as the call. If no definition is found, then the compiler searches for a definition in the enclosing module. If no definition is found, the compiler searches the imported modules in the order that they were imported. If no definition is found in any of these modules, then the compiler will issue an warning\footnote{A warning is issued instead of an error.  This allows users to test incomplete programs with missing definitions.}, assuming the symbol is defined in  the global module.

It is possible for two imported modules to contain different definitions that have the same name. When multiple names match a call, the order of the imported items determines which definition is used. Picat allows users to use qualified names to explicitly select a definition. A module-qualified call is a call preceded by a module name and '.' without intervening whitespace. 

\section*{Example}
\begin{verbatim}
% qsort.pi
module qsort.

sort([]) = [].
sort([H|T]) = 
    sort([E : E in T, E =< H]) ++ [H] ++ sort([E : E in T, E > H]).

% isort.pi
module isort.

sort([]) = [].
sort([H|T]) = insert(H,sort(T)).

private
insert(X,[]) = [X].
insert(X,Ys@[Y|_]) = Zs, X =< Y => Zs = [X|Ys].
insert(X,[Y|Ys]) = [Y|insert(X,Ys)].
\end{verbatim}
The module \texttt{qsort.pi} defines a function named \texttt{sort} using quick sort, and the module \texttt{isort} defines a function of the same name using insertion sort. In the following session, both modules are used.
\begin{verbatim}
picat> load("qsort")
picat> load("isort")
picat> L = sort([2,1,3])
L = [1,2,3]
picat> L = qsort.sort([2,1,3])
L = [1,2,3]
picat> L = isort.sort([2,1,3])
L = [1,2,3]
\end{verbatim}
As \texttt{sort} is also defined in the \texttt{basic} module, which is preloaded, that function is used for the command \texttt{L = sort([2,1,3])}.

Module names are just atoms. Consequently, it is possible to bind a variable to a module name. Nevertheless, in a module-qualified call $M.C$, the module name can never be a variable. Recall that the dot notation is also used to access attributes and to call predicates and functions. The notation $M.C$ is treated as a call or an attribute if $M$ is not an atom.

Suppose that users want to define a function named \texttt{generic\_sort(M,L)} that sorts list \texttt{L} using the \texttt{sort} function defined in module \texttt{M}. Users cannot just call \texttt{M.sort(L)}, since \texttt{M} is a variable. Users can, however, select a function based on the value held in \texttt{M} by using function facts\index{function fact} as follows:
\begin{verbatim}
generic_sort(qsort,L) = qsort.sort(L).
generic_sort(isort,L) = isort.sort(L).
\end{verbatim}

\section{Binding Higher-Order Calls}\index{higher-order call}
Because Picat forbids variable module qualifiers and terms in dot notations, it is impossible to create module-qualified higher-order terms. For a higher-order call, if the compiler knows the name of the higher-order term, as in \texttt{findall(X,$member(X,L)$)}\index{\texttt{findall}}\index{\texttt{member/2}}, then it searches for a definition for the name, just like it does for a normal call. However, if the name is unknown, as in \texttt{apply(F,X,Y)}\index{\texttt{apply}}, then the compiler generates code to search for a definition. For a higher-order call to \texttt{call/N} or \texttt{apply/N}, the runtime system searches modules in the following order:
\begin{enumerate}
\item The implicitly imported built-in modules \texttt{basic}, \texttt{io}, \texttt{math},  and \texttt{sys}.
\item The current list of loaded modules that is returned by the built-in function call \texttt{loaded\_modules()}, excluding the pre-imported built-in modules.
\item The global module.
\end{enumerate}
As private symbols are compiled away at compile time, higher-order terms can never reference private symbols. Due to the overhead of runtime search, the use of higher-order calls is discouraged.

\ignore{
\section{Accessing Attributes of Modules}
A function with no argument that is defined with one function fact\index{function fact} in a module is called an \emph{attribute} of the module. For example, the \texttt{math} module contains a function named \texttt{pi}\index{\texttt{pi}}, where
\begin{verbatim}
pi = 3.14159.    
\end{verbatim}
The advantage of treating no-arg functions as attribute-value pairs is that users can use the dot notation to access values. For example, users can use \texttt{math.pi}\index{\texttt{pi}} to retrieve the value that is associated with \texttt{pi}\index{\texttt{pi}} in the module \texttt{math}. 

Users can use no-argument functions in order to simulate C-style enum types. 

\section*{Example}
\begin{verbatim}
module color.

black = 0.
red = 1.
blue = 2.
green = 3.
white = 4.
cyan = 5.
yellow = 6.
magenta = 7.
\end{verbatim}
For a color, say \texttt{red}, users can retrieve the integer that is associated with it by using \texttt{color.red}. Note that a dot notation is an expression, but is not a valid term.  Therefore, a dot notation cannot occur in a head pattern. 

}
\section{Library Modules}
Picat comes with a library of standard modules, described in separate chapters. The function \texttt{sys.loaded\_modules()}\index{\texttt{loaded\_modules/0}} returns a list of modules that are currently in the system.
\ignore{
\end{document}
}
\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:io}I/O}
Picat has an \texttt{io} module for reading input from files and writing output to files.  The \texttt{io} module is imported by default.

The \texttt{io} module contains functions and predicates that read from a file, write to a file, reposition the read/write pointer within a file, redirect input and output, and create temporary files and pipes.

The \texttt{io} module uses file descriptors\index{file descriptor} to read input from files, and to write output to files.  A \emph{file descriptor}\index{file descriptor} is a structure that encodes file descriptor\index{file descriptor} data, including an index in a file descriptor table\index{file descriptor table} that stores information about opened files.  The following example reads data from one file, and writes the data into another file.

\subsection*{Example}
\begin{verbatim}
rw =>
     Reader = open("input_file.txt"),
     Writer = open("output_file.txt", write),
     L = read_line(Reader),
     while (L != end_of_file)
            println(Writer, L),
            flush(Writer),
            L := read_line(Reader)
     end,
     close(Reader),
     close(Writer).
\end{verbatim}

\section{Opening a File}
There are two functions for opening a file.  Both of them are used in the previous example.
\begin{itemize}
\item \texttt{open($Name$) = $FD$}\index{\texttt{open/1}}: The $Name$ parameter is a filename that is represented as a string.  This function opens the file with a default \texttt{read} mode.
\item \texttt{open($Name$,$Mode$) = $FD$}\index{\texttt{open/2}}:\index{read mode}\index{write mode}\index{append mode} The $Mode$ parameter is one of the four atoms: \texttt{read}, \texttt{write}, or \texttt{append}.  The \texttt{read} atom is used for reading from a file; if the file does not exist, or the program tries to write to the file, then the program will throw an error.  The \texttt{write} atom is used for reading from a file and writing to a file; if the file already exists, then the file will be overwritten.  The \texttt{append} atom is similar to the write atom; however, if the file already exists, then data will be appended at the end of the pre-existing file.  
\end{itemize}

\section{Reading from a File}
The \texttt{io} module has at least one function for reading data into each primitive data type.  It also has functions for reading characters, tokens, strings, and bytes.  Recall that strings are stored as lists of single-character atoms.

The \texttt{read} functions in the \texttt{io} module take a file descriptor\index{file descriptor} as the first parameter.  This file descriptor\index{file descriptor} is the same descriptor that the \texttt{open}\index{\texttt{open/1}}\index{\texttt{open/2}} function returns. The parameter can be omitted if it is the standard input file \texttt{stdin}.

\begin{itemize}
\item \texttt{read\_int($FD$) = $Int$}\index{\texttt{read\_int/1}}: This function reads a single integer from the file that is represented by $FD$. It throws an {\tt input\_mismatch} exception if $FD$ is at the end of the file or the next token at $FD$ is not an integer.

\item \texttt{read\_int() = $Int$}\index{\texttt{read\_int/0}}: This function is the same as \texttt{read\_int(stdin)}.
\item \texttt{read\_real($FD$) = $Real$}\index{\texttt{read\_real/1}}: This function reads a single real number from the file that is represented by $FD$. It throws an {\tt input\_mismatch} exception if $FD$ is at the end of the file or the next token at $FD$ is not a number.
\item \texttt{read\_real() = $Real$}\index{\texttt{read\_real/0}}: This function is the same as \texttt{read\_real(stdin)}.
\item \texttt{read\_char($FD$) = $Val$}\index{\texttt{read\_char/1}}: This function reads a single UTF-8 character from the file that is represented by $FD$. It returns {\tt end\_of\_file} if $FD$ is at the end of the file.
\item \texttt{read\_char() = $Val$}\index{\texttt{read\_char/0}}: This function is the same as \texttt{read\_char(stdin)}.
\item \texttt{read\_char($FD$,$N$) = $String$}\index{\texttt{read\_char/2}}: This function reads up to $N$ UTF-8 characters from the file that is represented by $FD$.  It returns a string that contains the characters that were read.
\item \texttt{read\_char\_code($FD$) = $Val$}\index{\texttt{read\_char\_code/1}}: This function reads a single UTF-8 character from the file that is represented by $FD$ and returns its code point. It returns -1 if $FD$ is at the end of the file.
\item \texttt{read\_char\_code() = $Val$}\index{\texttt{read\_char\_code/0}}: This function is the same as \texttt{read\_char\_code(stdin)}.
\item \texttt{read\_char\_code($FD$,$N$) = $List$}\index{\texttt{read\_char\_code/2}}: This function reads up to $N$ UTF-8 characters from the file that is represented by $FD$.  It returns a list of code points of the characters that were read.
\item \texttt{read\_picat\_token($FD$,$TokenType$,$TokenValue$)}\index{\texttt{read\_picat\_token/3}}: This predicate reads a single Picat token from the file that is represented by $FD$. $TokenType$ is the type and $TokenValue$ is the value of the token. $TokenType$ is one of the following: \texttt{atom}, \texttt{end\_of\_file}, \texttt{end\_of\_rule}, \texttt{integer}, \texttt{punctuation}, \texttt{real},  \texttt{string},  \texttt{underscore}, and \texttt{var}.
\item \texttt{read\_picat\_token($TokenType$,$TokenValue$)}\index{\texttt{read\_picat\_token/2}}: This predicate reads a token from \texttt{stdin}.
\item \texttt{read\_picat\_token($FD$) = $TokenValue$}\index{\texttt{read\_picat\_token/1}}: This function reads a single Picat token from the file that is represented by $FD$ and returns the token value.
\item \texttt{read\_picat\_token() = $TokenValue$}\index{\texttt{read\_picat\_token/0}}: This function is the same as the above, except that it reads from {\tt stdin}.
\item \texttt{read\_term($FD$) = $Term$}\index{\texttt{read\_term/1}}: This function reads a single Picat term from the file that is represented by $FD$.  The term must be followed by a dot  `\texttt{.}' and at least one whitespace character.  This function consumes the dot symbol.  The whitespace character is not stored in the returned string.
\item \texttt{read\_term() = $Term$}\index{\texttt{read\_term/0}}: This function is the same as \texttt{read\_term(stdin)}.
\item \texttt{read\_line($FD$) = $String$}\index{\texttt{read\_line/1}}: This function reads a string from the file that is represented by $FD$, stopping when either a newline (`\texttt{$\backslash$r$\backslash$n}' on Windows, and `\texttt{$\backslash$n}' on Unix) is read, or the \texttt{end\_of\_file} atom is returned.  The newline is not stored in the returned string.
\item \texttt{read\_line() = $String$}\index{\texttt{read\_line/0}}: This function is the same as \texttt{read\_line(stdin)}.
\item \texttt{readln($FD$) = $String$}\index{\texttt{readln/1}}: This function does the same thing as \texttt{read\_line}\index{\texttt{read\_line/1}}.
\item \texttt{readln() = $String$}\index{\texttt{readln/0}}: This function is the same as \texttt{readln(stdin)}.
\item \texttt{read\_byte($FD$) = $Val$}\index{\texttt{read\_byte/1}}: This function reads a single byte from the file that is represented by $FD$.
\item \texttt{read\_byte() = $Val$}\index{\texttt{read\_byte/0}}: This function is the same as \texttt{read\_byte(stdin)}.
\item \texttt{read\_byte($FD$,$N$) = $List$}\index{\texttt{read\_byte/2}}: This function reads up to $N$ bytes from the file that is represented by $FD$.  It returns the list of bytes that were read. 
\item \texttt{read\_file\_bytes($File$) = $List$}\index{\texttt{read\_file\_bytes/1}}: This function reads an entire byte file into a list. 
\item \texttt{read\_file\_bytes() = $List$}\index{\texttt{read\_file\_bytes/0}}: This function reads an entire byte file from the console into a list.
\item \texttt{read\_file\_chars($File$) = $String$}\index{\texttt{read\_file\_chars/1}}: This function reads an entire character file into a string. 
\item \texttt{read\_file\_chars() = $String$}\index{\texttt{read\_file\_chars/0}}: This function reads an entire character file from the console into a string. 
\item \texttt{read\_file\_codes($File$) = $List$}\index{\texttt{read\_file\_codes/1}}: This function reads UTF-8 codes of an entire character file into a list. 
\item \texttt{read\_file\_codes() = $List$}\index{\texttt{read\_file\_codes/0}}: This function reads UTF-8 codes of an entire character file from the console into a list. 
\item \texttt{read\_file\_lines($File$) = $Lines$}\index{\texttt{read\_file\_lines/1}}: This function reads an entire character file into a list of line strings.  
\item \texttt{read\_file\_lines() = $Lines$}\index{\texttt{read\_file\_lines/0}}: This function reads an entire character file from the console into a list of line strings.  
\item \texttt{read\_file\_terms($File$) = $Lines$}\index{\texttt{read\_file\_terms/1}}: This function reads an entire text file into a list of terms. In the file, each term must be terminated by `.' followed by at least one white space.
\item \texttt{read\_file\_terms() = $Lines$}\index{\texttt{read\_file\_terms/0}}: This function reads an entire text file from the console into a list of terms.
\end{itemize}

There are cases when the \texttt{read\_char($FD$,$N$)}\index{\texttt{read\_char/2}}, and \texttt{read\_byte($FD$,$N$)}\index{\texttt{read\_byte/2}} functions will read fewer than $N$ values.  One case occurs when the end of the file is encountered.  Another case occurs when reading from a pipe.  If a pipe is empty, then the \texttt{read} functions wait until data is written to the pipe.  As soon as the pipe has data, the \texttt{read} functions read the data.  If a pipe has fewer than $N$ values when a read occurs, then these three functions will return a string that contains all of the values that are currently in the pipe, without waiting for more values.  In order to determine the actual number of elements that were read, after the functions return, use \texttt{length($List$)}\index{\texttt{length/1}} to check the length of the list that was returned.

The \texttt{io} module also has functions that peek at the next value in the file without changing the current file location.  This means that the next \texttt{read} or \texttt{peek} function will return the same value, unless the read/write pointer is repositioned or the file is modified.

\begin{itemize}
\item \texttt{peek\_char($FD$) = $Val$}\index{\texttt{peek\_char/1}}
\item \texttt{peek\_byte($FD$) = $Val$}\index{\texttt{peek\_byte/1}}
\end{itemize}

\subsection{End of File}
The end of a file is detected through the \texttt{end\_of\_file}\index{\texttt{end\_of\_file}} atom.  If the input function returns a single value, and the read/write pointer is at the end of the file, then the \texttt{end\_of\_file}\index{\texttt{end\_of\_file}} atom is returned.  If the input function returns a list, then the end-of-file behavior is more complex.   If no other values have been read into the list, then the \texttt{end\_of\_file}\index{\texttt{end\_of\_file}} atom is returned.  However, if other values have already been read into the list, then reaching the end of the file causes the function to return the list, and the \texttt{end\_of\_file}\index{\texttt{end\_of\_file}} atom will not be returned until the next input function is called.

Instead of checking for \texttt{end\_of\_file}\index{\texttt{end\_of\_file}}, the \texttt{at\_end\_of\_stream}\index{\texttt{at\_end\_of\_stream/1}} predicate can be used to monitor a file descriptor\index{file descriptor} for the end of a file.

\begin{itemize}
\item \texttt{at\_end\_of\_stream($FD$)}\index{\texttt{at\_end\_of\_stream/1}}: The \texttt{at\_end\_of\_stream}\index{\texttt{at\_end\_of\_stream/1}} predicate is demonstrated in the following example. 
\end{itemize}

\subsection*{Example}
\begin{verbatim}
rw =>
     Reader = open("file1.txt"),
     Writer = open("file2.txt", write),
     while (not at_end_of_stream(Reader))
            L := read_line(Reader),
            println(Writer, L),
            flush(Writer)
     end,
     close(Reader),
     close(Writer).
\end{verbatim}

The advantage of using the \texttt{at\_end\_of\_stream}\index{\texttt{at\_end\_of\_stream/1}} predicate instead of using the \texttt{end\_of\_file}\index{\texttt{end\_of\_file}} atom is that \texttt{at\_end\_of\_stream}\index{\texttt{at\_end\_of\_stream/1}} immediately indicates that the end of the file was reached, even if the last \texttt{read} function read values into a list. In the first example in this chapter, which used the \texttt{end\_of\_file}\index{\texttt{end\_of\_file}} atom, an extra \texttt{read\_line}\index{\texttt{read\_line/1}} function was needed before the end of the file was detected.  In the above example, which used \texttt{at\_end\_of\_stream}\index{\texttt{at\_end\_of\_stream/1}}, \texttt{read\_line}\index{\texttt{read\_line/1}} was only called if there was data remaining to be read.

\section{Writing to a File}
The \texttt{write} and \texttt{print} predicates take a file descriptor\index{file descriptor} as the first parameter.  The file descriptor\index{file descriptor} is the same descriptor that the \texttt{open}\index{\texttt{open/1}}\index{\texttt{open/2}} function returns. If the file descriptor is \texttt{stdout}, then the parameter can be omitted.
\begin{itemize}
\item \texttt{write($FD$,$Term$)}\index{\texttt{write/2}}: This predicate writes $Term$ to a file.  Single-character lists are treated as strings.  Strings are double-quoted, and atoms are single-quoted when necessary.  This predicate does not print a newline, meaning that the next write will begin on the same line.
\item \texttt{write($Term$)}\index{\texttt{write/1}}: This predicate is the same as \texttt{write(stdout,$Term$)}.
\item \texttt{write\_byte($FD$,$Bytes$)}\index{\texttt{write\_byte/2}}: This predicate writes a single byte or a list of bytes to a file.
\item \texttt{write\_byte($Bytes$)}\index{\texttt{write\_byte/1}}: This predicate is the same as \texttt{write\_byte(stdout,$Bytes$)}.
\item \texttt{write\_char($FD$,$Chars$)}\index{\texttt{write\_char/2}}: This predicate writes a single character or a list of characters to a file. The characters are not quoted. When writing a single-character atom $Char$, \texttt{write\_char($FD$,$Char$)} is the same as \texttt{print($FD$,$Char$)}, but \texttt{write\_char} is faster than \texttt{print}.
\item \texttt{write\_char($Chars$)}\index{\texttt{write\_char/1}}: This predicate is the same as \texttt{write\_char(stdout,$Chars$)}.
\item \texttt{write\_char\_code($FD$,$Codes$)}\index{\texttt{write\_char\_code/2}}: This predicate writes a single character or a list of characters of the given code or list of codes to a file.
\item \texttt{write\_char\_code($Codes$)}\index{\texttt{write\_char\_code/1}}: This predicate is the same as the above, except that it writes to \texttt{stdout}.

\item \texttt{writeln($FD$,$Term$)}\index{\texttt{writeln/2}}: This predicate writes $Term$ and a newline, meaning that the next write will begin on the next line.
\item \texttt{writeln($Term$)}\index{\texttt{writeln/1}}: This predicate is the same as \texttt{writeln(stdout,$Term$)}.
\item \texttt{writef($FD$,$Format$,$Args\ldots$)}\index{\texttt{writef}}: This predicate is used for formatted writing, where the $Format$ parameter contains format characters that indicate how to print each of the arguments in the $Args$ parameter. The number of arguments in $Args\ldots$ cannot exceed 16.
\end{itemize}
Note that these predicates write both primitive values and compound values.

The \texttt{writef}\index{\texttt{writef}} predicate includes a parameter that specifies the string that is to be formatted.  The $Format$ parameter is a string that contains format characters.  Format characters take the form \texttt{\%[flags][width][.precision]specifier}.  Only the percent sign and the specifier are mandatory.  \emph{Flags} can be used for justification and padding.  The \emph{width} is the minimum number of characters that are to be printed.  The \emph{precision} is the number of characters that are to be printed after the number's radix point.  Note that the width includes all characters, including the radix point and the characters that follow it.  The \emph{specifier} indicates the type of data that is to be written.  A specifier can be one of the C format specifiers \texttt{\%\%}, \texttt{\%c},\footnote{The specifier \texttt{\%c} can only be used to print ASCII characters. Use the specifier \texttt{\%w} to print UTF-8 characters.}  \texttt{\%d}, \texttt{\%e}, \texttt{\%E}, \texttt{\%f}, \texttt{\%g}, \texttt{\%G}, \texttt{\%i}, \texttt{\%o}, \texttt{\%s}, \texttt{\%u}, \texttt{\%x}, and \texttt{\%X}.  In addition, Picat uses the specifier \texttt{\%n} for newlines, and uses \texttt{\%w} for terms.  For details, see Appendix \ref{chapter:format}.

\subsection*{Example}
\begin{verbatim}
formatted_print =>
    FD = open("birthday.txt",write),
    Format1 = "Hello, %s.  Happy birthday!  ",
    Format2 =  "You are %d years old today.  ", 
    Format3 =  "That is %.2f%% older than you were last year.",
    writef(FD, Format1, "Bob"),
    writef(FD, Format2, 7),
    writef(FD, Format3, ((7.0 - 6.0) / 6.0) * 100),
    close(FD).
\end{verbatim}

This writes, ``\texttt{Hello, Bob.  Happy birthday!  You are 7 years old today.  That is 16.67\% older than you were last year.}''
    
The \texttt{io} module also has the three \texttt{print} predicates.  
\begin{itemize}
\item \texttt{print($FD$,$Term$)}\index{\texttt{print/2}}: This predicate prints $Term$ to a file.  Unlike the \texttt{write}\index{\texttt{write/2}} predicates, the \texttt{print}\index{\texttt{print/2}} predicates do not place quotes around strings and atoms. 
\item \texttt{print($Term$)}\index{\texttt{print/1}}: This predicate is the same as \texttt{print(stdout,$Term$)}.
\item \texttt{println($FD$,$Term$)}\index{\texttt{println/2}} This predicate prints $Term$ and a newline.
\item \texttt{println($Term$)}\index{\texttt{println/1}} This predicate is the same as \texttt{println(stdout,$Term$)}.
\item \texttt{printf($FD$,$Format$,$Args\ldots$)}\index{\texttt{printf}}: This predicate is the same as \texttt{writef}\index{\texttt{writef}}, except that \texttt{printf}\index{\texttt{printf}} uses \texttt{print}\index{\texttt{print/2}} to display the arguments in the $Args$ parameter, while \texttt{writef}\index{\texttt{writef}} uses \texttt{write} to display the arguments in the $Args$ parameter. The number of arguments in $Args\ldots$ cannot exceed 16.
\end{itemize}

The following example demonstrates the differences between the \texttt{write}\index{\texttt{write/1}} and \texttt{print}\index{\texttt{print/1}} predicates.  
\subsection*{Example}
\begin{verbatim}
picat> write("abc")
[a,b,c]
picat> write([a,b,c])
[a,b,c]
picat> write('a@b')
'a@b'
picat> writef("%w %s%n",[a,b,c],"abc")
[a,b,c] abc
picat> print("abc")
abc
picat> print([a,b,c])
abc
picat> print('a@b')
a@b
picat> printf("%w %s%n",[a,b,c],"abc")
abc abc
\end{verbatim}

\section{Flushing and Closing a File}
The \texttt{io} module has one predicate to flush a file stream, and one predicate to close a file stream.
\begin{itemize}
\item \texttt{flush($FD$)}\index{\texttt{flush/1}}: This predicate causes all buffered data to be written without delay.
\item \texttt{close($FD$)}\index{\texttt{close/1}}: This predicate causes the file to be closed, releasing the file's resources, and removing the file from the file descriptor table\index{file descriptor table}.  Any further attempts to write to the file descriptor\index{file descriptor} without calling \texttt{open}\index{\texttt{open/1}}\index{\texttt{open/2}} will cause an error to be thrown.
\end{itemize}
\ignore{
\section{Repositioning I/O Pointers Within Files}
Sometimes, sequential file access is not enough.  Picat provides functions and predicates that allow a program to access and to modify its current location in a file.  These built-ins are demonstrated in the following example.
\subsection*{Example}
\begin{verbatim}
rw =>
     Writer = open("bond.txt", write),
     println(Writer, " Bond, James The name is."),
     flush(Writer),
     close(Writer),
     Reader = open("bond.txt", read),
     CS = sizeof_char(),
     setpos(Reader, 13 * CS)
     L = read_char(Reader, 11),
     print(L), % "The name is"
     rewind(Reader),
     L := read_char(Reader, 13),
     print(L), % " Bond, James "
     seek(Reader, -12 * CS, current),
     L := read_char(Reader, 4),
     print(L), % "Bond"
     seek(Reader, 1 * CS, end)
     C = read_char(Reader),
     print(C), % "."
     close(Reader).     
\end{verbatim}

The above example prints ''\texttt{The name is Bond, James Bond.}" if there are no errors during I/O.  The following five functions and predicates are used for repositioning file locations.
\begin{itemize}
\item \texttt{getpos($FD$) = $Pos$}\index{\texttt{getpos/1}}: This function returns the current file position, indicating the offset in the number of bytes from the beginning of the file.
\item \texttt{setpos($FD$,$Pos$)}\index{\texttt{setpos/2}}: This predicate changes the current file position of the read/write pointer to $Pos$, which is the number of bytes from the beginning of the file.
\item \texttt{rewind($FD$)}\index{\texttt{rewind/1}}: This predicate repositions the read/write pointer at the beginning of the file.
\item \texttt{seek($FD$,$Offset$,$From$)}\index{\texttt{seek/3}}: This predicate is similar to \texttt{setpos}\index{\texttt{setpos/2}}, because both predicates change the position of the read/write pointer.  However, the \texttt{seek}\index{\texttt{seek/3}} predicate uses two arguments to indicate the file location.  The $Offset$ argument indicates the number of bytes to move.  The $From$ argument is an atom.  If $From$ is \texttt{beginning}, then \texttt{seek}\index{\texttt{seek/3}} will move the read/write pointer to $Offset$ bytes from the beginning of the file.  If $From$ is \texttt{current}, then \texttt{seek}\index{\texttt{seek/3}} will move the read/write pointer to $Offset$ bytes from the current position.  This is the only case where $Offset$ can be negative, because a negative offset indicates that the read/write pointer should be moved backwards.  If $From$ is \texttt{end}, then \texttt{seek}\index{\texttt{seek/3}} will move the read/write pointer to $Offset$ bytes before the end of the file; note that, although the pointer is moved backwards from the end of the file, $Offset$ must be a positive number.  
\item \texttt{sizeof\_char() = $Size$}\index{\texttt{sizeof\_char/0}}: The bytesize of a character can differ on different systems.  Therefore, the \texttt{sizeof\_char}\index{\texttt{sizeof\_char/0}} function indicates the size of a character, in bytes, on the current system.  The \texttt{getpos}\index{\texttt{getpos/1}}, \texttt{setpos}\index{\texttt{setpos/2}}, and \texttt{seek}\index{\texttt{seek/3}} functions all indicate offsets in bytes.  If you want to show how many \emph{characters} to move the read/write pointer, use the \texttt{sizeof\_char}\index{\texttt{sizeof\_char/0}} function, and multiply the $Offset$ or $Pos$ parameter by the result, as shown in the previous example.  Note that if you seek to the middle of a character while performing character I/O, the program will have unpredictable behavior.    
\end{itemize}
The repositioning functions have no effect if they are passed the file descriptor\index{file descriptor} of standard input, standard output, or standard error.  The \texttt{getpos}\index{\texttt{getpos/1}} function will return $0$, while the \texttt{setpos}\index{\texttt{setpos/2}}, \texttt{seek}\index{\texttt{seek/3}}, and \texttt{rewind}\index{\texttt{rewind/1}} functions will not change the file pointer location.
}
\section{Standard File Descriptors}
The atoms \texttt{stdin}\index{\texttt{stdin}}, \texttt{stdout}\index{\texttt{stdout}}, and \texttt{stderr}\index{\texttt{stderr}} represent the file descriptors\index{file descriptor} for standard input, standard output, and standard error.  These atoms allow the program to use the input and output functions of the \texttt{io} module to read from and to write to the three standard streams. 
\ignore{
An advantage of using these atoms is that they can be used to allow the user to redirect standard input, standard output, and standard error to files, as shown in the following section.
}

\ignore{
\section{Redirection}

The following example shows how to redirect standard input and standard output to files.  This allows the program to read from and to write to files by using the functions and predicates that are defined in the \texttt{basic} module.

\subsection*{Example}
\begin{verbatim}
rw1 =>
     Reader = open("input_file.txt"),
     Writer = open("output_file.txt", write),
     close(stdin),
     InFD = dup(Reader),  % Redirects standard input
     close(stdout),
     OutFD = dup(Writer), % Redirects standard output
     close(Reader),
     close(Writer),
     L = read_line(),
     while (not at_end_of_stream(InFD))
            L := read_line(), % Reads from input_file.txt
            writeln(L)        % Writes to output_file.txt
     end.

rw2 =>
     Reader = open("input_file.txt"),
     Writer = open("output_file.txt", write),
     dup2(Reader, stdin),  % Redirects standard input
     dup2(Writer, stdout), % Redirects standard output
     close(Reader),
     close(Writer),
     L = read_line(),
     while (not at_end_of_stream(stdin))
            L := read_line(), % Reads from input_file.txt
            writeln(L)        % Writes to output_file.txt
     end.
\end{verbatim}

The above example uses the \texttt{dup}\index{\texttt{dup/1}} and \texttt{dup2}\index{\texttt{dup2/2}} built-ins.
\begin{itemize}
\item \texttt{dup($FD$) = $NewFD$}\index{\texttt{dup/1}}:  This function modifies the program's file descriptor table\index{file descriptor table}.  It takes the lowest available file descriptor\index{file descriptor}, and adds it to the program's file descriptor table\index{file descriptor table}. Then, \texttt{dup}\index{\texttt{dup/1}} copies the name of $FD$'s file to the new file descriptor\index{file descriptor}.  The \texttt{dup}\index{\texttt{dup/1}} function returns the new file descriptor\index{file descriptor}.
\item \texttt{dup2($FromFD$,$ToFD$)}\index{\texttt{dup2/2}}:  This predicate modifies the program's file descriptor table\index{file descriptor table}, performing two operations.  First, \texttt{dup2}\index{\texttt{dup2/2}} closes the entry to which $ToFD$ points in the file descriptor table\index{file descriptor table}.  Then, \texttt{dup2}\index{\texttt{dup2/2}} copies the name of the file of $FromFD$ to $ToFD$ in the file descriptor table\index{file descriptor table}.
\end{itemize}

If the above examples do not throw any errors, then they close standard input, copying \texttt{input\_file.txt} to the file descriptor\index{file descriptor} that is usually reserved for standard input.  Then, they close standard output, copying \texttt{output\_file.txt} to the file descriptor\index{file descriptor} number that is usually reserved for standard output.  At this point, \texttt{input\_file.txt} and \texttt{output\_file.txt} each have two entries in the file descriptor table\index{file descriptor table}.  Then, since \texttt{Reader} and \texttt{Writer} will not be used, their file descriptors\index{file descriptor} are closed.  At this point, \texttt{input\_file.txt} and \texttt{output\_file.txt} each have one entry in the file descriptor table\index{file descriptor table}.  Finally, the program uses \texttt{read\_line}\index{\texttt{read\_line/0}} and \texttt{writeln}\index{\texttt{writeln/1}}, both of which are defined in the \texttt{basic} Picat module, in order to read from and to write to the files.

Notice the differences between \texttt{rw1} and \texttt{rw2}.  The \texttt{rw1} example explicitly closes \texttt{stdin}\index{\texttt{stdin}}.  Then, the lowest available file descriptor\index{file descriptor} is the file descriptor\index{file descriptor} that was used for \texttt{stdin}\index{\texttt{stdin}}, so \texttt{dup}\index{\texttt{dup/1}} copies \texttt{input\_file.txt} to the file descriptor\index{file descriptor} that is usually reserved for standard input.  Then, \texttt{rw1} explicitly closes \texttt{stdout}\index{\texttt{stdout}}.  The lowest available file descriptor\index{file descriptor} is the file descriptor\index{file descriptor} that was used for \texttt{stdout}\index{\texttt{stdout}}, so \texttt{dup}\index{\texttt{dup/1}} copies \texttt{output\_file.txt} to the file descriptor\index{file descriptor} that is usually reserved for standard output.  Unlike \texttt{rw1}, the \texttt{rw2} example explictly indicates standard input and standard output as the destination file descriptors\index{file descriptor} for \texttt{dup2}\index{\texttt{dup2/2}}.  The \texttt{dup2}\index{\texttt{dup2/2}} predicate closes \texttt{stdin}\index{\texttt{stdin}} and \texttt{stdout}\index{\texttt{stdout}} automatically.

Note that a program's file descriptor table\index{file descriptor table} is initialized as soon as it begins execution.  Each process\index{process} has its own file descriptor table\index{file descriptor table}.  The \texttt{dup}\index{\texttt{dup/1}} and \texttt{dup2}\index{\texttt{dup2/2}} built-ins only modify the current program's file descriptor table\index{file descriptor table}, which is destroyed when the program finishes execution.  Therefore, if a program is executed multiple times, then \texttt{stdin}\index{\texttt{stdin}}, \texttt{stdout}\index{\texttt{stdout}}, and \texttt{stderr}\index{\texttt{stderr}} are initialized to their default values before execution.  

Note that standard input, standard output, and standard error do not need to be explicitly closed, even if they are redirected.  This is why the program does not call \texttt{close}\index{\texttt{close/1}} after the while loop terminates.

The following example shows how to use \texttt{dup2}\index{\texttt{dup2/2}} together with the \texttt{process} module in order to imitate the command ''\texttt{ls -l > dir.txt}".

\subsection*{Example}
\begin{verbatim}
import io, process.

ls =>
    Writer = open("dir.txt", write),
    dup2(Writer, stdout),
    close(Writer),
    process.exec("ls", "-l").
\end{verbatim}

The \texttt{dup2}\index{\texttt{dup2/2}} predicate redirects standard output to ''\texttt{dir.txt}".  Therefore, when \texttt{exec}\index{\texttt{exec}} is called, the output of ''\texttt{ls}", will also redirect to ''\texttt{dir.txt}".  For more information about the \texttt{exec}\index{\texttt{exec}} predicate, see Chapter \ref{chapter:process}.

\section{Temporary Files and Pipes}
The \texttt{io} module has four functions whose purpose is to create new files and file descriptors\index{file descriptor} for the purposes of communication.

\subsection{Temporary Files}
The \texttt{mktmp}\index{\texttt{mktmp/0}} function is used to create temporary files.
\begin{itemize}
\item \texttt{mktmp() = $FD$}\index{\texttt{mktmp/0}}: This function creates a temporary file in the file system, and returns a file descriptor\index{file descriptor} for the temporary file.  This file descriptor\index{file descriptor} can be used to read from and to write to the file.  The temporary file exists until the file descriptor\index{file descriptor} is closed, or until termination of the program that called the \texttt{mktmp}\index{\texttt{mktmp/0}} function.
\end{itemize}

\subsection{Pipes}
Pipes are special files that are used for interprocess\index{process} communication.  Picat provides three functions and predicates for the creation of pipes.
\begin{itemize}
\item \texttt{mkpipe() = $FD\_Map$}\index{\texttt{mkpipe/0}}:  This function creates an unnamed pipe\index{unnamed pipe}, which is stored in in kernel memory.  This function returns a map with two keys.  The \texttt{readFD} key represents the file descriptor\index{file descriptor} that is used to read from the pipe.  The \texttt{writeFD} key represents the file descriptor\index{file descriptor} used to write to the pipe.  The unnamed pipe\index{unnamed pipe} can only be used by related processes\index{process}.  It is removed from kernel memory when all processes\index{process} that use the pipe have terminated.  Note that if the pipe is empty, and no process\index{process} has the pipe open for writing, then the \texttt{read} functions will return \texttt{end\_of\_file}\index{\texttt{end\_of\_file}}.
\item \texttt{mkfifo($Path$)}\index{\texttt{mkfifo/1}}:  This predicate creates a named pipe\index{fifo}, or a \emph{FIFO}\index{fifo}, which is stored as a file in the location specified by $Path$.  The FIFO\index{fifo} can be used by unrelated processes\index{process}.  Like a regular file, the FIFO\index{fifo} remains in memory even if it is not currently being used by any processes\index{process}.  In order to remove the FIFO\index{fifo} from memory, use the \texttt{rm}\index{\texttt{rm/1}} predicate that is defined in the \texttt{os} module.
\item \texttt{mkfifo($Path$,$Mode$)}\index{\texttt{mkfifo/2}}:  This version of \texttt{mkfifo}\index{\texttt{mkfifo/2}} has a $Mode$ parameter.  This parameter is either a single atom or a list of two or three atoms.  The format of the atoms is specified by the regular expression \texttt{r?w?(u|g|o)}.  If the atom contains \texttt{r}, then it provides permission to read from the FIFO\index{fifo}.  If the atom contains \texttt{w}, then it provides permission to write to the FIFO\index{fifo}.  The second part of the atom indicates the receiver(s) of the permission, where \texttt{u} specifies the user, \texttt{g} specifies anybody who is in the user's group, and \texttt{o} specifies anybody who is not in the user's group.  At most one atom can exist for each of \texttt{u}, \texttt{g}, and \texttt{o}.  If a permission is not explicitly specified in the $Mode$ parameter, then the permission is not provided.  However, the \texttt{mkfifo($Path$)}\index{\texttt{mkfifo/1}} predicate provides a default permission list of \texttt{[rwu, rwg]}, which allows the user and the user's group to read from and to write to the FIFO\index{fifo}.
\end{itemize}

The following example demonstrates the difference between unnamed pipes\index{unnamed pipe} and named pipes\index{fifo}.
\subsection*{Example:}
\begin{verbatim}
% File 1
import io, process.

unnamed =>
    FDs = mkpipe(), % create the pipe
    ID = process.fork(),
    if (ID == 0)    % child process
       close(FDs.writeFD),
       reader(FDs.readFD)
    else            % parent process
       close(FDs.readFD),
       writer(FDs.writeFD)
    end.
    
reader(FD) =>
    Str = read_line(FD),
    close(FD).

writer(FD) =>
    writeln(FD, "Communicating"),
    close(FD).

% File 2
import io.

fifo =>
   mkfifo("fifo.txt", [rwu, rwg, rwo]),
   Writer = open("fifo.txt", append),
   foreach (I in 1..100)
            writeln(Writer, I)
   end,
   close(Writer).

% File 3 -- executed by any user some time after File 2 was executed
import io, os.

nofifo =>
   Reader = open("fifo.txt", read),
   while (not at_end_of_stream(Reader))
          I := read_int(Reader),
          write_int(I), % prints I to standard output
          writeln()
   end,
   close(Reader),
   os.rm("fifo.txt"). % deletes the fifo
\end{verbatim}

Notice the differences between the unnamed pipe\index{unnamed pipe} and the named pipe\index{fifo}.  The unnamed pipe\index{unnamed pipe} is used by two related processes\index{process}.  Each process\index{process} closes one of the pipe's file descriptors\index{file descriptor} immediately, and closes the other file descriptor\index{file descriptor} as soon as the process\index{process} finishes communicating.  As soon as the \texttt{unnamed} predicate finishes executing, the unnamed pipe\index{unnamed pipe} is removed from memory.  The named pipe\index{fifo} can be used by two unrelated processes\index{process}.  After the \texttt{fifo} predicate finishes executing, the named pipe\index{fifo} remains in memory until it is removed in the \texttt{nofifo} predicate.

For more information on processes\index{process}, see Chapter \ref{chapter:process}.

\subsection{A Note on Errors}
The functions and predicates in the \texttt{io} module can throw a large number of errors.  For example, attempts to read from and to write to a non-existent file descriptor\index{file descriptor} will generate an error.  Another error occurs when trying to create a file that already exists.  Errors can also be generated when the user tries to perform an operation on a file, such as writing to the file, when the user does not have permission to perform the operation.

In most cases, if an I/O error occurs, then Picat will throw \texttt{io\_error($ENo$,$EMsg$,$Source$)}, where $ENo$ is the error number, $EMsg$ is a string that indicates the error that occurred, and $Source$ is the goal that caused the error to occur.  

If the \texttt{open}\index{\texttt{open/1}}\index{\texttt{open/2}} function is unable to find the file that is passed to it, then the \texttt{open}\index{\texttt{open/1}}\index{\texttt{open/2}} function will throw \texttt{file\_not\_found($Earg$,$Source$)}, where $Earg$ is the name of the file, and $Source$ is the function or predicate that called \texttt{open}\index{\texttt{open/1}}\index{\texttt{open/2}}. 
}
\ignore{
\end{document}
}
\ignore{
\documentstyle[11pt]{report}
\textwidth 13.7cm
\textheight 21.5cm
\newcommand{\myimp}{\verb+ :- +}
\newcommand{\ignore}[1]{}
\def\definitionname{Definition}

\makeindex
\begin{document}
}
\chapter{\label{ch:actors}Event-Driven Actors and Action Rules}
Many applications require event-driven computing. For example, an interactive GUI system needs to react to UI events such as mouse clicks on UI components; a Web service provider needs to respond to service requests; a constraint propagator for a constraint needs to react to updates to the domains of the variables in the constraint. Picat provides action rules\index{action rule} for describing event-driven actors. An actor is a predicate call that can be delayed and can be activated later by events. Actors communicate with each other through event channels. 

\section{Channels, Ports, and Events}
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, named \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}, respectively. Many built-ins in Picat post events. When an attributed variable is instantiated, an event is posted to the \texttt{ins}-port\index{\texttt{ins}-port} of the variable. When the lower bound or upper bound of a variable's domain changes, an event  is posted to the \texttt{bound}-port\index{\texttt{bound}-port} of the variable. When an inner element $E$, which is neither the lower or upper bound, is excluded from the domain of a variable, $E$ is posted to the \texttt{dom}-port\index{\texttt{dom}-port} of the variable. When an arbitrary element $E$, which can be the lower or upper bound or an inner element, is excluded from the domain of a variable, $E$ is posted to the \texttt{any}-port\index{\texttt{any}-port} of the variable. The division of a channel into ports facilitates speedy handling of events. For better performance, the system posts an event to a port only when there are actors attached to the port. For example, if no actor is attached to a domain variable to handle exclusions of domain elements, then these events will never be posted.

The built-in \texttt{post\_event($X$,$T$)}\index{\texttt{post\_event/2}} posts the event term $T$ to the \texttt{dom}-port\index{\texttt{dom}-port} of the channel variable $X$.
\ignore{where $X$ can be a channel variable, a conjunction of channel variables \texttt{($X_1$,$X_2$,$\ldots$,$X_n$)}, or a disjunction of channel variables \texttt{($X_1$;$X_2$;$\ldots$;$X_n$)}. When $X$ is a conjunction, the event is posted to the actors attached to the \texttt{dom}-ports\index{\texttt{dom}-port} of \emph{all} of the channel variables; when $X$ is a disjunction, the event is posted to actors attached to the \texttt{dom}-port\index{\texttt{dom}-port} of at least one of the channels. For example, suppose that an actor is attached to variable $X_1$, but the actor is not attached to variable $X_2$; then, the actor will \emph{not} be activated by the call \texttt{post\_event(($X_1$,$X_2$),$T$)}\index{\texttt{post\_event/2}}, but the actor \emph{will} be activated by the call \texttt{post\_event(($X_1$;$X_2$),$T$)}\index{\texttt{post\_event/2}}. Operationally, \\ \texttt{post\_event(($X_1$;$X_2$),$T$)}\index{\texttt{post\_event/2}} is different from posting $T$ to $X_1$ and $X_2$ separately; if an actor is attached to both $X_1$ and $X_2$, then \texttt{post\_event(($X_1$;$X_2$),$T$)}\index{\texttt{post\_event/2}} causes the actor to be activated one time, while posting $T$ to $X_1$ and $X_2$ separately causes the actor to be activated twice.
}

The following built-ins are used to post events to one of a channel's four ports:
\begin{itemize}
\item \texttt{post\_event\_ins($X$)}\index{\texttt{post\_event\_ins/1}}: posts an event to the \texttt{ins}-port\index{\texttt{ins}-port} of the channel $X$. 
\item \texttt{post\_event\_bound($X$)}\index{\texttt{post\_event\_bound/1}}: posts an event to the \texttt{bound}-port\index{\texttt{bound}-port} of the channel $X$. 
\item \texttt{post\_event\_dom($X$,$T$)}\index{\texttt{post\_event\_dom/2}}: posts the term $T$ to the \texttt{dom}-port\index{\texttt{dom}-port} of the channel $X$.
\item \texttt{post\_event\_any($X$,$T$)}\index{\texttt{post\_event\_any/2}}: posts the event $T$ to the \texttt{any}-port\index{\texttt{any}-port} of the channel of $X$.
\end{itemize}
The call \texttt{post\_event($X$,$T$)}\index{\texttt{post\_event/2}} is the same as \texttt{post\_event\_dom($X$,$T$)}\index{\texttt{post\_event\_dom/2}}.  This means that the \texttt{dom}-port\index{\texttt{dom}-port} of a finite domain variable has two uses: posting exclusions of inner elements from the domain, and posting general term events. 

\section{Action Rules}
Picat provides \emph{action rules}\index{action rule} for describing the behaviors of actors. An action rule\index{action rule} takes the following form:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> $Head, Cond, \{Event\}\ $$=$$>$$\ Body$ 
\end{tabbing}
where $Head$ is an actor 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 that is activated by an event, an action rule\index{action rule} is said to be \emph{applicable} if the actor matches $Head$ and $Cond$ is true. A predicate for actors is defined with action rules\index{action rule} and non-backtrackable rules. It cannot contain backtrackable rules.

Unlike rules for a normal predicate or function, in which the conditions can contain any predicates, the conditions of the rules in a predicate for actors must be conjunctions of inline test predicates, such as type-checking built-ins (e.g., \texttt{integer($X$)}\index{\texttt{integer/1}} and \texttt{var($X$)}\index{\texttt{var/1}}) and comparison built-ins (e.g., equality test \texttt{$X$ == $Y$}, disequality test {\tt $X$ \verb+!+== $Y$}, and arithmetic comparison \texttt{$X$ $>$ $Y$}). This restriction ensures that no variables in an actor can be changed while the condition is executed.

For an actor that is activated by an event, the system searches the definition sequentially from the top for an applicable rule. If no applicable rule is found, then the actor fails. If an applicable rule is found, the system executes the body of the rule. If the body fails, then the actor also fails. The body cannot succeed more than once. The system enforces this by converting \texttt{$Body$} into \texttt{`once $Body$'}\index{\texttt{once/1}} if $Body$ contains calls to nondeterministic predicates. If the applied rule is an action rule\index{action rule}, then the actor is suspended after the body is executed, meaning that the actor is waiting to be activated again. If the applied rule is a normal non-backtrackable rule, then the actor vanishes after the body is executed. For each activation, only the first applicable rule is applied.

For a call and an action rule\index{action rule} `$Head, Cond, \{Event\}\ $$=$$>$$\ Body$', the call is registered as an actor if the call matches $Head$ and $Cond$ evaluates to \texttt{true}. The event pattern $Event$ implicitly specifies the ports to which the actor is attached, and the events that the actor watches. The following event patterns are allowed in $Event$:
\begin{itemize}
\item \texttt{event($X$,$T$)}: This is the general event pattern. The actor is attached to the \texttt{dom}-ports\index{\texttt{dom}-port} of the variables in $X$.  The actor will be activated by events posted to the \texttt{dom}-ports\index{\texttt{dom}-port}. $T$ must be a variable that does not occur before \texttt{event($X$,$T$)} in the rule.
\item \texttt{ins($X$)}: The actor is attached to the \texttt{ins}-ports\index{\texttt{ins}-port} of the variables in $X$.  The actor will be activated when a variable in $X$ is instantiated.
\item \texttt{bound($X$)}: The actor is attached to the \texttt{bound}-ports\index{\texttt{bound}-port} of the variables in $X$.  The actor will be activated when the lower bound or upper bound of the domain of a variable in $X$ changes.
\item \texttt{dom($X$)}: The actor is attached to the \texttt{dom}-ports\index{\texttt{dom}-port} of the variables in $X$.  The actor will be activated when an inner value is excluded from the domain of a variable in $X$. The actor is not interested in what value is actually excluded.
\item \texttt{dom($X$,$E$)}: This is the same as \texttt{dom($X$)}, except the actor is interested in the value $E$ that is excluded. $E$ must be a variable that does not occur before \texttt{dom($X$,$E$)} in the rule.
\item \texttt{dom\_any(X)}: The actor is attached to the \texttt{any}-ports\index{\texttt{any}-port} of the variables in $X$.  The actor will be activated when an arbitrary value, including the lower bound value and the upper bound value, is excluded from the domain of a variable in $X$.  The actor is not interested in what value is actually excluded. 
\item \texttt{dom\_any($X$,$E$)}: This is the same as \texttt{dom\_any($X$)}, except the actor is interested in the value $E$ that is actually excluded. $E$ must be a variable that does not occur before \texttt{dom\_any($X$,$E$)} in the rule.
\end{itemize}
In an action rule\index{action rule}, multiple event patterns can be specified.  After a call is registered as an actor on the channels, it will be suspended, waiting for events, unless the atom \texttt{generated} occurs in $Event$, in which case the actor will be suspended after $Body$ is executed.

The system has an event queue. After events are posted, they are added into the queue. Events are not handled until execution enters or exits a non-inline predicate or function. In other words, only non-inline predicates and functions can be interrupted, and inline predicates, such as \texttt{$X$ = $Y$}, and inline functions, such as \texttt{$X$ + $Y$}, are never interrupted by events.

\subsection*{Example}
Consider the following action rule:
\begin{verbatim}
      p(X), {event(X,T)} => writeln(T).
\end{verbatim}
The following gives a query and its output:
\begin{verbatim}
Picat> p(X), X.post_event(ping), X.post_event(pong)
ping
pong
\end{verbatim}
The call \texttt{p(X)} is an actor. After {\tt X.post\_event(ping)}, the actor is activated and the body of the action rule is executed, giving the output {\tt ping}. After \texttt{X.post\_event(pong)}, the actor is activated again, outputting {\tt pong}.


There is no primitive for killing actors or explicitly detaching actors from channels. As described above, an actor never disappears as long as action rules\index{action rule} are applied to it. An actor vanishes only when a normal rule is applied to it. Consider the following example.
\begin{verbatim}
      p(X,Flag), 
          var(Flag), 
          {event(X,T)}
      => 
          writeln(T),
          Flag = 1.
      p(_,_) => true.
\end{verbatim}
An actor defined here can only handle one event posting. After it handles an event, it binds the variable \texttt{Flag}. When a second event is posted, the action rule\index{action rule} is no longer applicable, causing the second rule to be selected.

One question arises here: what happens if a second event is never posted to \texttt{X}? In this case, the actor will stay forever. If users want to immediately kill the actor after it is activated once, then users have to define it as follows:
\begin{verbatim}
      p(X,Flag), 
          var(Flag), 
          {event(X,O),ins(Flag)},

      => 
          write(O),
          Flag = 1.
      p(_,_) => true.
\end{verbatim}
In this way, the actor will be activated again after \texttt{Flag} is bound to $1$, and will be killed after the second rule is applied to it.

\section{Lazy Evaluation}
The built-in predicate \texttt{freeze(X,Goal)}\index{\texttt{freeze/2}} is equivalent to `\texttt{once Goal}'\index{\texttt{once/1}}, but its evaluation is delayed until \texttt{X} is bound to a non-variable term. The predicate is defined as follows:
\begin{verbatim}
     freeze(X,Goal), var(X), {ins(X)} => true.
     freeze(X,Goal) => call(Goal).
\end{verbatim}
For the call \texttt{freeze(X,Goal)}\index{\texttt{freeze/2}}, if  \texttt{X} is a variable, then \texttt{X} is registered as an actor on the \texttt{ins}-port\index{\texttt{ins}-port} of \texttt{X}, and \texttt{X} is then suspended. Whenever \texttt{X} is bound, the event \texttt{ins} is posted to the \texttt{ins}-port\index{\texttt{ins}-port} of \texttt{X}, which activates the actor \texttt{freeze(X,Goal)}\index{\texttt{freeze/2}}. The condition \texttt{var(X)}\index{\texttt{var/1}} is checked. If true, the actor is suspended again; otherwise, the second rule is executed, causing the actor to vanish after it is rewritten into \texttt{once Goal}\index{\texttt{once/1}}.

The built-in predicate \texttt{different\_terms($T_1$,$T_2$)}\index{\texttt{different\_terms/2}} is a disequality constraint on terms $T_1$ and $T_2$. The constraint fails if the two terms are identical; it succeeds whenever the two terms are found to be different; it is delayed if no decision can be made because the terms are not sufficiently instantiated. The predicate is defined as follows:
\begin{verbatim}
import cp.

different_terms(X,Y) =>
    different_terms(X,Y,1).

different_terms(X,Y,B), var(X), {ins(X),ins(Y)} => true.
different_terms(X,Y,B), var(Y), {ins(X)} => true.
different_terms([X|Xs],[Y|Ys],B) =>
    different_terms(X,Y,B1),
    different_terms(Xs,Ys,B2),
    B #= (B1 #\/ B2).
different_terms(X,Y,B), struct(X), struct(Y) =>
    writeln(X), writeln(Y),											  
    if (X.name !== Y.name; X.length !== Y.length)
       B = 1
    else
       Bs = new_list(X.length),
       foreach (I in 1 .. X.length)
           different_terms(X[I],Y[I],Bs[I])
       end,
       max(Bs) #= B
    end.
different_terms(X,Y,B), X == Y => B = 0.
different_terms(X,Y,B) => B = 1.
\end{verbatim}
The call \texttt{different\_terms(X,Y,B)} is delayed if either \texttt{X} or \texttt{Y} is a variable. The delayed call watches \texttt{ins(X)} and  \texttt{ins(Y)} events. Once both \texttt{X} and \texttt{Y} become non-variable, the action rule\index{action rule} becomes inapplicable, and one of the subsequent rules will be applied. If \texttt{X} and \texttt{Y} are lists, then they are different if the heads are different (\verb+B1+), or if the tails are different (\verb+B2+).  This relationship is represented as the Boolean constraint \verb+ B #= (B1 #\/ B2)+. If \texttt{X} and \texttt{Y} are both structures, then they are different if the functor is different, or if any pair of arguments of the structures is different.


\section{Constraint Propagators}
A constraint propagator is an actor that reacts to updates of the domains of the variables in a constraint. The following predicate defines a propagator for maintaining arc consistency on \texttt{X} for the constraint \verb-X+Y #= C-:
\begin{verbatim}
   import cp.

   x_in_c_y_ac(X,Y,C), var(X), var(Y),
      {dom(Y,Ey)}
       =>         
      fd_set_false(X,C-Ey).
   x_in_c_y_ac(X,Y,C) => true.
\end{verbatim}
Whenever an inner element \texttt{Ey} is excluded from the domain of \texttt{Y}, this propagator is triggered to exclude \texttt{C-Ey}, which is the support of \texttt{Ey}, from the domain of \texttt{X}. For the constraint \verb-X+Y #= C-, users need to generate two propagators, namely,
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{x\_in\_c\_y\_ac(X,Y,C)} and \texttt{x\_in\_c\_y\_ac(Y,X,C)}
\end{tabbing}
to maintain the arc consistency. Note that in addition to these two propagators, users also need to generate propagators for maintaining interval consistency, because \texttt{dom(Y,Ey)} only captures exclusions of inner elements, and does not capture bounds. The following propagator maintains interval consistency for the constraint:
\begin{verbatim}
   import cp.

   x_add_y_eq_c_ic(X,Y,C), var(X), var(Y),
       {generated,ins(X),ins(Y),bound(X),bound(Y)}
   =>         
       X :: C-fd_max(Y) .. C-fd_min(Y),
       Y :: C-fd_max(X) .. C-fd_min(X).
   x_add_y_eq_c_ic(X,Y,C), var(X) =>
       X = C-Y.
   x_add_y_eq_c_ic(X,Y,C) =>
       Y = C-X.
\end{verbatim}
When both \texttt{X} and \texttt{Y} are variables, the propagator \texttt{x\_add\_y\_eq\_c\_ic(X,Y,C)} is activated whenever \texttt{X} and \texttt{Y} are instantiated, or whenever the bounds of their domains are updated. The body maintains the interval consistency of the constraint \verb-X+Y #= C-. The body is also executed when the propagator is generated. When either \texttt{X} or \texttt{Y} becomes non-variable, the propagator becomes a normal call, and vanishes after the variable \texttt{X} or \texttt{Y} is solved.

\ignore{
\section{Timers and Time Events}
In some applications, actors need to be activated regularly at a predefined time rate. For example, a clock animator is activated every second, and the scheduler in a time-sharing system switches control to the next process after a certain time quota elapses. To facilitate the description of time-related behavior of actors, Picat provides a module named \texttt{timer}.

The function \texttt{new\_timer($Interval$)}\index{\texttt{new\_timer/1}} returns a timer that posts a time event at the specified time rate. A timer runs as a separate thread\index{thread}, and starts ticking immediately after it is created. A timer itself is a channel. It posts the event \texttt{time} to itself in every $Interval$ milliseconds. A timer $T$ stops posting events after the predicate call \texttt{stop($T$)}\index{\texttt{stop/1}}. A stopped timer can be started again. A timer is destroyed after the call \texttt{kill($T$)}\index{\texttt{kill/1}} is executed.

\begin{itemize}
\item \texttt{new\_timer($Interval$) = $T$}\index{\texttt{new\_timer/1}}: \texttt{T} is a timer that posts a time event every $Interval$ milliseconds.
\item \texttt{new\_timer() = $T$}\index{\texttt{new\_timer/0}}: This is equivalent to \texttt{new\_timer(200)}\index{\texttt{new\_timer/1}}.
\item \texttt{start($T$)}\index{\texttt{start/1}}: Start the timer $T$. After a timer is created, it starts ticking immediately. Therefore, it is unnecessary to start a timer with this call. This predicate is used to restart a stopped timer.
\item \texttt{stop($T$)}\index{\texttt{stop/1}}: Stop the timer.
\item \texttt{kill($T$)}\index{\texttt{kill/1}}: Kill the timer.
\item \texttt{set\_interval($T$,$Interval$)}\index{\texttt{set\_interval/2}}: Reset the interval of the timer $T$ to $Interval$. The update is destructive, and the old value is not restored upon backtracking.
\item \texttt{get\_interval($T$) = $Interval$}\index{\texttt{get\_interval/1}}: Get the interval of the timer $T$.
\end{itemize}

\subsubsection*{Example}
\noindent
\begin{picture}(380,1)(0,0)
\put (0,0){\framebox(380,1)}
\end{picture}

\noindent
The following example shows two actors that behave in accordance with two timers.
\begin{verbatim}
go =>
    T1 = new_timer(100), 
    T2 = new_timer(1000),
    T1.add_actor(ping),
    T2.add_actor(pong),
    while (true) true end.

ping,{_} => writeln(ping).

pong,{_} => writeln(pong).
\end{verbatim}
\noindent
\begin{picture}(380,1)(0,0)
\put (0,0){\framebox(380,1)}
\end{picture}

\noindent
Note that the empty \texttt{while} loop in predicate \texttt{go} is needed to let the main thread run. Without it, the query \texttt{go} would succeed before any time event is posted, meaning that neither of the actors would get a chance to be activated.

}
%\section{Bottom-Up Evaluation of Datalog Rules}

\ignore{
\end{document}
}


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

\makeindex
\begin{document}

}
\chapter{\label{ch:constraints}Constraints}
Picat provides four solver modules, including \texttt{cp}, \texttt{sat}, \texttt{smt}, and \texttt{mip}, for modeling and solving constraint\index{constraint} satisfaction and optimization problems (CSPs).  All four of these modules implement the same set of constraints on integer-domain variables. The \texttt{mip} module also supports real-domain variables. In order to use a solver, users must first import the module. In order to make the symbols defined in a module available to the top level of the interpreter, users can use the built-in {\tt import} to import the module. The \texttt{mip} module requires Gurobi (\url{https://www.gurobi.com/}), Cbc (\url{ https://github.com/coin-or/Cbc}), or GLPK (\url{https://www.gnu.org/software/glpk/}). The \texttt{smt} module requires Z3 (\url{https://github.com/Z3Prover/z3/}) or CVC4 (\url{https://cvc4.github.io/}). Users can specify, as a solving option, a solver to be used if the module is \texttt{mip} or \texttt{smt}.

As the four modules have the same interface, this chapter describes the four modules together. Figure \ref{tab:cons_ops} shows the constraint\index{constraint} operators that are provided by Picat. Unless it is explicitly specified otherwise, the built-ins that are described in this chapter appear in all four modules. In the built-ins that are presented in this chapter, an integer-domain variable can also be an integer, unless it is explicitly specified to only be a variable.

\begin{table}[ht]
\caption{\label{tab:cons_ops}Constraint operators in Picat}
\begin{center}
\begin{tabular}{ |c|c| } \hline
Precedence & Operators  \\ \hline \hline
Highest    & \verb+::+, \verb+notin+,  \verb+#=+,  \verb+#!=+, \verb+#<+,  \verb+#=<+, \verb+#<=+, \verb+#>+, \verb+#>=+ \\ \hline 
           & \verb+#~+ \\ \hline 
           & \verb+#/\+ \\ \hline 
           & \verb+#^+ \\ \hline 
           & \verb+#\/+ \\ \hline 
           & \verb+#=>+ \\ \hline 
Lowest     & \verb+#<=>+ \\ \hline 
\end{tabular}
\end{center}
\end{table}

A constraint program normally poses a problem in three steps: (1) generate variables; (2) generate constraints 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 and possibly optimizes an objective function.

\subsection*{Example}
\begin{figure}[ht]
\begin{center}
\begin{verbatim}
    import cp.

    queens(N) =>
        Qs = new_array(N),
        Qs :: 1..N,
        foreach (I in 1..N-1, J in I+1..N)
            Qs[I] #!= Qs[J],
            abs(Qs[I]-Qs[J]) #!= J-I
        end,
        solve(Qs),
        writeln(Qs).
\end{verbatim}
\end{center}
\caption{\label{fig:nqueens} A program for N-queens.}
\end{figure}

This program in Figure \ref{fig:nqueens} imports the \texttt{cp} module in order to solve the $N$-queens problem. The same program runs with the SAT solver if \texttt{sat} is imported, runs with the SMT solver if \texttt{smt} is imported, and runs with the LP/MIP solver if \texttt{mip} is imported. The predicate \texttt{Qs :: 1..N} declares the domains of the variables. The operator \verb+#!=+ is used for inequality constraints. In arithmetic constraints, expressions are treated as terms, and it is unnecessary to enclose them with dollar-signs. The predicate \texttt{solve(Qs)}\index{\texttt{solve/1}} calls the solver in order to solve the array of variables \texttt{Qs}. For \texttt{cp}, \texttt{solve([ff],Qs)}\index{\texttt{solve/2}}, which always selects a variable that has the smallest domain (the so-called \emph{first-fail principle}\index{first-fail principle}), can be more efficient than \texttt{solve(Qs)}\index{\texttt{solve/1}}.


\section{Domain Variables}
A domain variable is an attributed variable that has a domain attribute. The Boolean domain is treated as a special integer domain where 1 denotes \texttt{true} and 0 denotes \texttt{false}. Domain variables are declared with the built-in predicate \texttt{$Vars$ :: $Exp$}. 

\begin{itemize}
\item \texttt{$Vars$ :: $Exp$}: This predicate restricts the domain or domains of $Vars$ to $Exp$.  $Vars$ can be either a single variable or a collection of variables.\footnote{A collection can be either a list or an array, where elements can be collections.} For integer-domain variables, $Exp$ must result in a list of integer values. For real-domain variables for the {\tt mip} module, $Exp$ must be an interval in the form \texttt{$L$..$U$}, where $L$ and $U$ are real values.
\end{itemize}

Domain variables, when being created, are usually represented internally by using intervals. An
interval turns to a bit vector when a hole occurs in the interval. The following built-in predicate can be used to reset the range or access the current range.
\begin{itemize}
\item \texttt{fd\_vector\_min\_max($Min$,$Max$)}: When the arguments are integers, this predicate specifies the range of bit vectors; when the arguments are variables, this predicate binds them to the current bounds of the range. The default range is {\tt -3200..3200}.
\index{\texttt{fd\_vector\_min\_max/2}}
\end{itemize}

The following built-ins are provided for domain variables.
\begin{itemize}
\item \texttt{$Vars$ notin $Exp$}: This predicate excludes values $Exp$ from the domain or domains of $Vars$, where $Vars$ and $Exp$ are the same as in \texttt{$Vars$ :: $Exp$}. This constraint cannot be applied to real-domain variables.
\item \texttt{fd\_degree($FDVar$) = $Degree$}\index{\texttt{fd\_degree/1}}: This function returns the number of propagators that are attached to $FDVar$. This built-in is only provided by {\tt cp}.
\item \texttt{fd\_disjoint($FDVar1$,$FDVar2$)}\index{\texttt{fd\_disjoint/2}}: This predicate is true if $FDVar1$'s domain and $FDVar2$'s domain are disjoint.
\item \texttt{fd\_dom($FDVar$) = $List$}\index{\texttt{fd\_dom/1}}: This function returns the domain of $FDVar$ as a list,  where $FDVar$ is an integer-domain variable. If $FDVar$ is an integer, then the returned list contains the integer itself.
\item \texttt{fd\_false($FDVar$,$Elm$)}\index{\texttt{fd\_false/2}}: This predicate is true if the integer $Elm$ is not an element in the domain of $FDVar$.
\item \texttt{fd\_max($FDVar$) = $Max$}\index{\texttt{fd\_max/1}}: This function returns the upper bound of the domain of $FDVar$, where $FDVar$ is an integer-domain variable.
\item \texttt{fd\_min($FDVar$) = $Min$}\index{\texttt{fd\_min/1}}: This function returns the lower bound of the domain of \\ $FDVar$, where $FDVar$ is an integer-domain variable.
\item \texttt{fd\_min\_max($FDVar$,$Min$,$Max$)}\index{\texttt{fd\_min\_max/3}}: This predicate binds $Min$ to the lower bound of the domain of $FDVar$, and binds $Max$ to the upper bound of the domain of $FDVar$, where $FDVar$ is an integer-domain variable.
\item \texttt{fd\_next($FDVar$,$Elm$) = $NextElm$}\index{\texttt{fd\_next/2}}: This function returns the next element of $Elm$ in $FDVar$'s domain. It throws an exception if $Elm$ has no next element in $FDVar$'s domain.
\item \texttt{fd\_prev($FDVar$,$Elm$) = $PrevElm$}\index{\texttt{fd\_prev/2}}: This function returns the previous element of $Elm$ in $FDVar$'s domain. It throws an exception if $Elm$ has no previous element in $FDVar$'s domain.
\item \texttt{fd\_set\_false($FDVar$,$Elm$)}\index{\texttt{fd\_set\_false/2}}: This predicate excludes the element $Elm$ from the domain of $FDVar$. If this operation results in a hole in the domain, then the domain changes from an interval representation into a bit-vector representation, no matter how big the domain is. This built-in is only provided by {\tt cp}.
\item \texttt{fd\_size($FDVar$) = $Size$}\index{\texttt{fd\_size/1}}: This function returns the size of the domain of $FDVar$,  where $FDVar$ is an integer-domain variable.
\item \texttt{fd\_true($FDVar$,$Elm$)}\index{\texttt{fd\_true/2}}: This predicate is true if the integer $Elm$ is an element in the domain of $FDVar$.
\item \texttt{new\_dvar() = $FDVar$}\index{\texttt{new\_dvar/0}}: This function creates a new domain variable with the default domain, which has the bounds \texttt{-72057594037927935..72057594037927935} on 64-bit computers and \texttt{-268435455..268435455} on 32-bit computers.\footnote{Note that incorrect results may be caused by overflows or underflows.}
\end{itemize}

\section{Table constraints}
A \emph{table constraint}\index{table constraint}, or an \emph{extensional constraint}\index{extensional constraint}, over a tuple of variables specifies a set of tuples that are allowed (called \emph{positive}) or disallowed (called \emph{negative}) for the variables. A positive constraint takes the form \texttt{table\_in($DVars$,$R$)}\index{\texttt{table\_in/2}}, where $DVars$ is either a tuple of variables $\{X_1,\ldots,X_n\}$ or a list of tuples of variables, and $R$ is a list of tuples in which each tuple takes the form $\{a_1,\ldots,a_n\}$, where $a_i$ is an integer or the \textit{don't-care} symbol $*$\index{don't-care symbol}.  A negative constraint takes the form \texttt{table\_notin($DVars$,$R$)}\index{\texttt{table\_notin/2}}.

\subsection*{Example}
The following example solves a toy crossword puzzle. One variable is used for each cell in the grid, so each slot corresponds to a tuple of variables. Each word is represented as a tuple of integers, and each slot takes on a set of words of the same length as the slot. Recall that the function \texttt{ord($Char$)}\index{\texttt{ord/1}} returns the code of $Char$, and that the function \texttt{chr($Code$)}\index{\texttt{chr/1}} returns the character of $Code$.

\begin{verbatim}
    import cp.

    crossword(Vars) =>
        Vars = [X1,X2,X3,X4,X5,X6,X7], 
        Words2 = [{ord('I'),ord('N')},
                  {ord('I'),ord('F')},
                  {ord('A'),ord('S')},
                  {ord('G'),ord('O')},
                  {ord('T'),ord('O')}],
        Words3 = [{ord('F'),ord('U'),ord('N')},
                  {ord('T'),ord('A'),ord('D')},
                  {ord('N'),ord('A'),ord('G')},
                  {ord('S'),ord('A'),ord('G')}],
        table_in([{X1,X2},{X1,X3},{X5,X7},{X6,X7}], Words2),
        table_in([{X3,X4,X5},{X2,X4,X6}], Words3),
        solve(Vars),
        writeln([chr(Code) : Code in Vars]).
\end{verbatim}

\section{Arithmetic Constraints}
An arithmetic constraint takes the form
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{$Exp1$ $Rel$ $Exp2$} 
\end{tabbing}
where $Exp1$ and $Exp2$ are arithmetic expressions, and $Rel$ is one of the constraint operators:  \verb+#=+, \verb+#!=+, \verb+#<+, \verb+#=<+, \verb+#<=+, \verb+#>+, or \verb+#>=+. The operators \verb+#=<+ and \verb+#<=+ are the same, meaning less than or equal to. An arithmetic expression is made from integers, variables, arithmetic functions, and constraints. The following arithmetic functions are allowed: \texttt{+} (addition), \texttt{-} (subtraction), \texttt{*} (multiplication), \texttt{/} (truncated integer division), \texttt{//} (truncated integer division), \texttt{count}, \texttt{div} (floored integer division), \texttt{mod}, \texttt{**} (power), \texttt{abs}, \texttt{min}, \texttt{max}, and \texttt{sum}.  Except for index notations, array comprehensions and list comprehensions, which are interpreted as function calls as in normal expressions, expressions in arithmetic constraints are treated as terms, and it is unnecessary to enclose them with dollar-signs. In addition to the numeric operators, the following functions are allowed in constraints:\footnote{Dot notation should not be used for functions in constraint expressions, as such functions are always evaluated eagerly.}
\begin{itemize}
\item \texttt{cond($BoolConstr$,$ThenExp$,$ElseExp$)}: This expression is the same as\\ \texttt{$BoolConstr$*$ThenExp$+(1-$BoolConstr$)*$ElseExp$}.
\item \texttt{count($V$,$Collection$)}: The number of times $V$ occurs in $Collection$, where $Collection$ is a nested collection of domain variables.\footnote{A nested collection is recursively defined. It can be variable, a number, a list, or an array. If it is a list or an array, then the elements can be nested collections.}
\item \texttt{max($Collection$)}: The maximum of $Collection$, where $Collection$ is a nested collection of domain variables.
\item \texttt{max($Exp1$,$Exp2$)}: The maximum of $Exp1$ and $Exp2$.
\item \texttt{min($Collection$)}: The minimum of $Collection$, where $Collection$ is a nested collection of domain variables.
\item \texttt{min($Exp1$,$Exp2$)}: The minimum of $Exp1$ and $Exp2$.
\item \texttt{prod($Collection$)}: The product of $Collection$, where $Collection$ is a nested collection of domain variables.
\item \texttt{sum($Collection$)}: The sum of $Collection$, where $Collection$ is a nested collection of domain variables.
\end{itemize}
When a constraint occurs in an arithmetic expression, it is evaluated to 1 if it is satisfied and 0 if it is not satisfied.

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

    go =>
        M = {{0,3,2,3,0,0,0,0},
             {0,0,0,0,0,0,5,0},
             {0,1,0,0,0,1,0,0},
             {0,0,2,0,2,0,0,0},
             {0,0,0,0,0,0,0,5},
             {0,4,0,0,2,0,0,1},
             {0,0,0,0,0,2,0,3},
             {0,0,0,0,0,0,0,0}},
        maxflow(M,1,8).

    maxflow(M,Source,Sink) =>
        N = M.length,
        X = new_array(N,N),
        foreach (I in 1..N, J in 1..N)
            X[I,J] :: 0..M[I,J]
        end,
        foreach (I in 1..N, I != Source, I != Sink)
            sum([X[J,I] : J in 1..N]) #= sum([X[I,J] : J in 1..N]) 
        end,
        Total #= sum([X[Source,I] : I in 1..N]),
        Total #= sum([X[I,Sink] : I in 1..N]),
        solve([$max(Total)],X),
        writeln(Total),
        writeln(X).
\end{verbatim}
This program uses MIP to solve the maximum integer flow problem. Given the capacity matrix \texttt{M} of a directed graph, the start vertex \texttt{Source}, and the destination vertex \texttt{Sink}, the predicate \texttt{maxflow(M,Source,Sink)} finds a maximum flow from \texttt{Source} to \texttt{Sink} over the graph. When two vertices are not connected by an arc, the capacity is given as 0. The first foreach loop specifies the domains of the variables. For each variable \texttt{X[I,J]}, the domain is restricted to integers between 0 and the capacity, \texttt{M[I,J]}. If the capacity is 0, then the variable is immediately instantiated to 0. The next foreach loop posts the conservation constraints. For each vertex \texttt{I}, if it is neither the source nor the sink, then its total incoming flow amount 
\begin{verbatim}
    sum([X[J,I] : J in 1..N])
\end{verbatim}
is equal to the total outgoing flow amount 
\begin{verbatim}
    sum([X[I,J] : J in 1..N]).
\end{verbatim}
The total flow amount is the total outgoing amount from the source, which is the same as the total incoming amount to the sink.

\section{Boolean Constraints}
A Boolean constraint takes one of the following forms:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \verb+#~+ $BoolExp$ \\
\>   $BoolExp$ \verb+#/\+ $BoolExp$ \\
\>   $BoolExp$ \verb+#^+ $BoolExp$ \\
\>   $BoolExp$ \verb+#\/+ $BoolExp$ \\
\>   $BoolExp$ \verb+#=>+ $BoolExp$ \\
\>   $BoolExp$ \verb+#<=>+ $BoolExp$ \\
\end{tabbing}
$BoolExp$ is either a Boolean constant (0 or 1), a Boolean variable (an integer-domain variable with the domain [0,1]), an arithmetic constraint, a domain constraint (in the form of \texttt{$Var$ :: $Domain$} or \texttt{$Var$ notin $Domain$}), or a Boolean constraint. As shown in Table \ref{tab:cons_ops}, the operator \verb+#~+ has the highest precedence, and the operator \verb+#<=>+ has the lowest precedence. Note that the Boolean constraint operators have lower precedence than the arithmetic constraint operators. So the constraint 
\begin{verbatim}
     X #!= 3 #/\ X#!= 5 #<=> B
\end{verbatim}
is interpreted as
\begin{verbatim}
     ((X #!= 3) #/\ (X#!= 5)) #<=> B.
\end{verbatim}
The Boolean constraint operators are defined as follows.
\begin{itemize}
\item {\tt \verb+#~+ $BoolExp$}: This constraint is 1 iff $BoolExp$ is equal to 0.
\item {\tt $BoolExp1$ \verb+#/\+ $BoolExp2$}: This constraint is 1 iff both $BoolExp1$ and $BoolExp2$ are 1.
\item {\tt $BoolExp1$ \verb+#^+ $BoolExp2$}:  This constraint is 1 iff exactly one of $BoolExp1$ and $BoolExp2$ is 1.
\item {\tt $BoolExp1$ \verb+#\/+ $BoolExp2$}:  This constraint is 1 iff $BoolExp1$ or $BoolExp2$ is 1.
\item {\tt $BoolExp1$ \verb+#=>+ $BoolExp2$}: This constraint is 1 iff $BoolExp1$ implies $BoolExp2$.
\item {\tt $BoolExp1$ \verb+#<=>+ $BoolExp2$}: This constraint is 1 iff $BoolExp1$ and $BoolExp2$ are equivalent.
\end{itemize}

\section{Global Constraints}
A global constraint is a constraint over multiple variables. A global constraint can normally be translated into a set of smaller constraints, such as arithmetic and Boolean constraints. If the \texttt{cp} module is used, then global constraints are not translated into smaller constraints; rather, they are compiled into special propagators that maintain a certain level of consistency for the constraints. In Picat, constraint propagators are encoded as action rules\index{action rule}. If the \texttt{sat} module is used, then global constraints are translated into smaller constraints before being translated further into conjunctive normal form. If the \texttt{mip} module is used, then global constraints are decomposed into equality and disequality constraints.

Picat provides the following global constraints.

\begin{itemize}
\item \texttt{acyclic($Vs$,$Es$)}\index{\texttt{acyclic/2}}: This constraint ensures that the \textit{undirected}\index{undirected graph} graph represented by $Vs$ and $Es$ contains no cycles, where $Vs$ is a list of pairs of the form $\{V,B\}$ and $Es$ is a list of triplets of the form $\{V_1,V_2,B\}$. A pair $\{V,B\}$ in $Vs$, where $V$ is a ground term and $B$ is a Boolean variable, denotes that $V$ is in the graph if and only if $B = 1$. A triplet $\{V_1,V_2,B\}$ denotes that $V_1$ is connected with $V_2$  by an edge in the graph if and only if $B = 1$ and both $V_1$ and $V_2$ are in the graph. Note that the graph to be constructed is assumed to be undirected. If there exists a triplet $\{V_1,V_2,B\}$ in $Es$, then the triplet $\{V_2,V_1,B\}$ will be added to $Es$ if it is not specified.

\item \texttt{acyclic\_d($Vs$,$Es$)}\index{\texttt{acyclic\_d/2}}: This constraint ensures that the \textit{directed}\index{directed graph} graph represented by $Vs$ and $Es$ contains no cycles, where $Vs$ and $Es$ are the same as those in \texttt{acyclic($Vs$,$Es$)}, except that the graph is directed.
    
\item \texttt{all\_different($FDVars$)}\index{\texttt{all\_different/1}}: This constraint ensures that each pair of variables in the list or array $FDVars$ is different. This constraint is compiled into a set of inequality constraints. For each pair of variables $V1$ and $V2$ in $FDVars$, \texttt{all\_different($FDVars$)}\index{\texttt{all\_different/1}} generates the constraint {\tt $V1$ \verb+#!=+ $V2$}.

\item \texttt{all\_distinct($FDVars$)}\index{\texttt{all\_distinct/1}}: This constraint is the same as \texttt{all\_different}\index{\texttt{all\_different/1}}, but for the \texttt{cp} module it maintains a higher level of consistency. For some problems, this constraint is faster and requires fewer backtracks than \texttt{all\_different}\index{\texttt{all\_different/1}}, and, for some other problems, this constraint is slower due to the overhead of consistency checking.

\item \texttt{all\_different\_except\_0($FDVars$)}\index{\texttt{all\_different\_except\_0/1}}: This constraint is true if all non-zero values in $FDVars$ are different.
\item \texttt{assignment($FDVars1$,$FDVars2$)}\index{\texttt{assignment/2}}: This constraint ensures that $FDVars2$ is a \emph{dual assignment} of $FDVars1$, i.e., if the $i$th element of $FDVars1$ is $j$, then the $j$th element of $FDVars2$ is $i$. The constraint can be defined as:
\begin{verbatim}
    assignment(Xs,Ys) =>
        N = Xs.length,
        (var(Ys) -> Ys = new_list(N); true),
        Xs :: 1..N,
        Ys :: 1..N,
        foreach (I in 1..N, J in 1..N)
            X[I] #= J #<=> Y[J] #= I
        end.
\end{verbatim}

\item \texttt{at\_least($N$,$L$,$V$)}:\index{\texttt{atleast/3}} This constraint succeeds if there are at least $N$ elements in $L$ that are equal to $V$, where $N$ and $V$ must be integer-domain variables, and $L$ must be a list of integer-domain variables.

\item \texttt{at\_most($N$,$L$,$V$)}:\index{\texttt{atmost/3}} This constraint succeeds if there are at most $N$ elements in $L$ that are equal to $V$, where $N$ and $V$ must be integer-domain variables, and $L$ must be a list of integer-domain variables.

\item \texttt{circuit($FDVars$)}\index{\texttt{circuit/1}}: Let $FDVars$ be a list of variables \texttt{[$X_1,X_2,\ldots,X_N$]}, where each \texttt{$X_i$} has the domain $1..N$. A valuation $X_1 = v_1$, $X_2 = v_2$, $\ldots$, $X_n = v_n$ satisfies the constraint if \texttt{1 -> $v_1$, 2 -> $v_2$, ..., n -> $v_n$} forms a Hamiltonian cycle\index{Hamiltonian cycle}. This constraint ensures that each variable has a different value, and that the graph that is formed by the assignment does not contain any sub-cycles. For example, for the constraint\index{\texttt{circuit/1}} 
\begin{verbatim}
    circuit([X1,X2,X3,X4])
\end{verbatim}
\texttt{[3,4,2,1]} is a solution, but \texttt{[2,1,4,3]} is not, because the graph \texttt{1 -> 2, 2 -> 1, 3 -> 4, 4 -> 3} contains two sub-cycles.
\item \texttt{count($V$,$FDVars$,$Rel$,$N$)}\index{\texttt{count/4}}:  In this constraint, $V$ and $N$ are integer-domain variables, $FDVars$ is a list of integer-domain variables, and $Rel$ is an arithmetic constraint operator (\verb+#=+,  \verb+#!=+,  \verb+#>+,  \verb+#>=+,  \verb+#<+,  \verb+#=<+, or \verb+#<=+). Let $Count$ be the number of elements in $FDVars$ that are equal to $V$. The constraint is true iff $Count$ $Rel$ $N$ is true. This constraint can be defined as follows:
\begin{verbatim}
    count(V,L,Rel,N) =>
       sum([V #= E : E in L]) #= Count,
       call(Rel,Count,N).
\end{verbatim}
\item \texttt{count($V$,$FDVars$,$N$)}\index{\texttt{count/3}}: This constraint is the same as \texttt{count}($V$,$FDVars$,\verb+#=+,$N$).

\item \texttt{cumulative($Starts$,$Durations$,$Resources$,$Limit$)}\index{\texttt{cumulative/4}}: This constraint is useful for describing and solving scheduling problems. The arguments $Starts$, $Durations$, and $Resources$ are lists of integer-domain variables of the same length, and $Limit$ is an integer-domain variable. Let $Starts$ be \texttt{[$S_1$, $S_2$, $\ldots$, $S_n$]}, $Durations$ be \texttt{[$D_1$, $D_2$, $\ldots$, $D_n$]}, and $Resources$ be \texttt{[$R_1$, $R_2$, $\ldots$, $R_n$]}. For each job \texttt{$i$}, \texttt{$S_i$} represents the start time, \texttt{$D_i$} represents the duration, and \texttt{$R_i$} represents the units of resources needed. $Limit$ is the limit on the units of resources available at any time. This constraint ensures that the limit cannot be exceeded at any time.

\item \texttt{decreasing($L$)}\index{\texttt{decreasing/1}}: The sequence (an array or a list) $L$ is in (non-strictly) decreasing order.

\item \texttt{decreasing\_strict($L$)}\index{\texttt{decreasing\_strict/1}}: The sequence (an array or a list) $L$ is in strictly decreasing order.

\item \texttt{diffn($RectangleList$)}\index{\texttt{diffn/1}}: This constraint ensures that no two rectangles in $RectangleList$ overlap with each other. A rectangle in an $n$-dimensional space is represented by a list of $2\times n$ elements \texttt{[$X_1$, $X_2$, $\ldots$, $X_n$, $S_1$, $S_2$, $\ldots$, $S_n$]}, where \texttt{$X_i$} is the starting coordinate of the edge in the $i$th dimension, and \texttt{$S_i$} is the size of the edge.

\item \texttt{disjunctive\_tasks($Tasks$)}\index{\texttt{disjunctive\_tasks/1}}: $Tasks$ is a list of terms.  Each term has the form \\ \texttt{disj\_tasks($S_1$,$D_1$,$S_2$,$D_2$)}, where \texttt{$S_1$} and \texttt{$S_2$} are two integer-domain variables, and \texttt{$D_1$} and \texttt{$D_2$} are two positive integers. This constraint is equivalent to posting the disjunctive constraint $S_1$+$D_1$ \verb+#=<+ $S_2$ \verb+#\/+ $S_2$+$D_2$ \verb+#=<+ $S_1$ for each term in $Tasks$; however the constraint may be more efficient, because it converts the disjunctive tasks into global constraints. 

\item \texttt{element($I$,$List$,$V$)}\index{\texttt{element/3}}: This constraint is true if the $I$th element of $List$ is $V$, where $I$ and $V$ are integer-domain variables, and $List$ is a list of integer-domain variables.

\item \texttt{element0($I$,$List$,$V$)}\index{\texttt{element0/3}}: This constraint is the same as \texttt{element($I$,$List$,$V$)}, except that 0-based, rather than 1-based, indexing is used.

\item \texttt{exactly($N$,$L$,$V$)}\index{\texttt{exactly/3}}: This constraint succeeds if there are exactly $N$ elements in $L$ that are equal to $V$, where $N$ and $V$ must be integer-domain variables, and $L$ must be a list of integer-domain variables.

\item \texttt{global\_cardinality($List$,$Pairs$)}\index{\texttt{global\_cardinality/2}}: Let $List$ be a list of integer-domain variables \texttt{[$X_1$, $\ldots$, $X_d$]}, and $Pairs$ be a list of pairs \texttt{[$K_1$-$V_1$, $\ldots$, $K_n$-$V_n$]}, where each key \texttt{$K_i$} is a unique integer, and each \texttt{$V_i$} is an integer-domain variable. The constraint is true if every element of $List$ is equal to some key, and, for each pair \texttt{$K_i$-$V_i$}, exactly \texttt{$V_i$} elements of $List$ are equal to \texttt{$K_i$}. This constraint can be defined as follows:
\begin{verbatim}
    global_cardinality(List,Pairs) =>
        foreach ($Key-V in Pairs) 
            sum([B : E in List, B#<=>(E#=Key)]) #= V
        end.
\end{verbatim}

\item \texttt{hcp($Vs$,$Es$)}\index{\texttt{hcp/2}}: This constraint ensures that the \textit{directed}\index{directed graph} graph represented by $Vs$ and $Es$ forms a Hamiltonian cycle\index{Hamiltonian cycle}, where $Vs$ is a list of pairs of the form $\{V,B\}$, and $Es$ is a list of triplets of the form $\{V_1,V_2,B\}$. A pair $\{V,B\}$ in $Vs$, where $V$ is a ground term and $B$ is a Boolean variable, denotes that $V$ is in the graph if and only if $B = 1$. A triplet $\{V_1,V_2,B\}$ denotes that $V_1$ is connected to $V_2$  by an edge in the graph if and only if $B = 1$. The \texttt{circuit} and \texttt{subcircuit} constraints can be implemented as follows by using \texttt{hcp}:
\begin{verbatim}
    circuit(L) =>
        N = len(L),
        L :: 1..N,
        Vs = [{I,1} : I in 1..N],
        Es = [{I,J,B} : I in 1..N, 
                        J in fd_dom(L[I]), 
                        J !== I, 
                        B #<=> L[I] #= J],
        hcp(Vs,Es).

    subcircuit(L) =>
        N = len(L),
        L :: 1..N,
        Vs = [{I,B} : I in 1..N, 
                      B #<=> L[I] #!= I],
        Es = [{I,J,B} : I in 1..N, 
                        J in fd_dom(L[I]), 
                        J !== I, 
                        B #<=> L[I] #= J],
        hcp(Vs,Es).
\end{verbatim}

\item \texttt{hcp($Vs$,$Es$,$K$)}\index{\texttt{hcp/3}}:  This constraint is the same as \texttt{hcp($Vs$,$Es$)}, except that it also constrains the number of vertices in the graph to be $K$. 

\item \texttt{hcp\_grid($A$)}\index{\texttt{hcp\_grid/1}}:  This constraint ensures that the \textit{grid}\index{grid graph} graph represented by $A$, which is a two-dimensional array of Boolean (0/1) variables, forms a Hamiltonian cycle. In a grid graph, each cell is directly connected horizontally and vertically, but not diagonally, to its neighbors. Only cells labeled 1 are considered as vertices of the graph. This constraint is implemented as follows by using \texttt{hcp}:
\begin{verbatim}
    hcp_grid(A) =>
        NRows = len(A),
        NCols = len(A[1]),
        Vs = [{(R,C), A[R,C]} : 
                    R in 1..NRows, 
                    C in 1..NCols],
        Es = [{(R,C), (R1,C1), _} : 
                    R in 1..NRows, 
                    C in 1..NCols,
                    (R1,C1) in neibs(A,NRows,NCols,R,C)],
        hcp(Vs,Es).

    neibs(A,NRows,NCols,R,C) = 
        [(R1,C1) : (R1,C1) in [(R-1,C), (R+1,C), 
                               (R,C-1), (R,C+1)],
                    R1 >= 1, R1 =< NRows,
                    C1 >= 1, C1 =< NCols, 
                    A[R1,C1] !== 0].
\end{verbatim}

\item \texttt{hcp\_grid($A$,$Es$)}\index{\texttt{hcp\_grid/2}}: This constraint is the same as \texttt{hcp\_grid($A$)}, except that it also restricts the edges to $Es$, which consists of triplets of the form $\{V_1,V_2,B\}$. In a triplet in $Es$, $V_1$ and $V_2$ take the form $(R,C)$, where $R$ is a row number and $C$ is a column number, and $B$ is a Boolean variable, which denotes that $V_1$ is connected to $V_2$  by an edge in the graph if and only if $B = 1$. If $Es$ is a variable, then it is bound to the edges of the grid graph.  

\item \texttt{hcp\_grid($A$,$Es$,$K$)}\index{\texttt{hcp\_grid/3}}: This constraint is the same as\\ \texttt{hcp\_grid($A$,$Es$)}, except that it also constrains the number of vertices in the graph to be $K$. 

\item \texttt{increasing($L$)}\index{\texttt{increasing/1}}: The sequence (an array or a list) $L$ is in (non-strictly) increasing order.

\item \texttt{increasing\_strict($L$)}\index{\texttt{increasing\_strict/1}}: The sequence (an array or a list) $L$ is in strictly increasing order.

\item \texttt{lex\_le($L_1$,$L_2$)}\index{\texttt{lex\_le/2}}: The sequence (an array or a list) $L_1$ is lexicographically less than or equal to $L_2$.

\item \texttt{lex\_lt($L_1$,$L_2$)}\index{\texttt{lex\_lt/2}}: The sequence (an array or a list) $L_1$ is lexicographically less than $L_2$.

\item \texttt{matrix\_element($Matrix$,$I$,$J$,$V$)}\index{\texttt{matrix\_element/4}}: This constraint is true if the entry at $<$$I$,$J$$>$ in $Matrix$ is $V$, where $I$, $J$, and $V$ are integer-domain variables, and $Matrix$ is an two-dimensional array of integer-domain variables.

\item \texttt{matrix\_element0($Matrix$,$I$,$J$,$V$)}\index{\texttt{matrix\_element0/4}}: This constraint is the same as the above, except that it uses 0-based, rather than 1-based, indexing for the entries of the matrix. 

\item \texttt{neqs($NeqList$)}\index{\texttt{neqs/1}}: $NeqList$ is a list of inequality constraints of the form $X$ \verb+#!=+ $Y$, where $X$ and $Y$ are integer-domain variables. This constraint is equivalent to the conjunction of the inequality constraints in $NeqList$, but it extracts \texttt{all\_distinct}\index{\texttt{all\_distinct/1}} constraints from the inequality constraints. 

\item \texttt{nvalue($N$,$List$)}\index{\texttt{nvalue/2}}: The number of distinct values in $List$ is $N$, where $List$ is a list of integer-domain variables.

\item \texttt{path($Vs$,$Es$,$Src$,$Dest$)}\index{\texttt{path/4}}: This constraint ensures that the \textit{undirected}\index{undirected graph} graph represented by $Vs$ and $Es$ is a path from $Src$ to $Dest$, where $Vs$ is a list of pairs of the form $\{V,B\}$, $Es$ is a list of triplets of the form $\{V_1,V_2,B\}$, $Src$ is a vertex, and $Dest$ is a vertex or a list of vertices. A pair $\{V,B\}$ in $Vs$, where $V$ is a ground term representing a vertex and $B$ is a Boolean variable, denotes that $V$ is in the graph if and only if $B = 1$. A triplet $\{V_1,V_2,B\}$ denotes that $V_1$ is connected with $V_2$  by an edge in the graph if and only if $B = 1$ and both $V_1$ and $V_2$ are in the graph. Note that the graph to be constructed is assumed to be undirected. If there exists a triplet $\{V_1,V_2,B\}$ in $Es$, then the triplet $\{V_2,V_1,B\}$ will be added to $Es$ if it is not specified.

\item \texttt{path\_d($Vs$,$Es$,$Src$,$Dest$)}\index{\texttt{path\_d/4}}: This constraint ensures that the \textit{directed}\index{directed graph} graph represented by $Vs$ and $Es$ is a path from $Src$ to $Dest$, where $Vs$ and $Es$ are the same as those in \texttt{path($Vs$,$Es$,$Src$,$Dest$)}, except that the graph is directed.

\item \texttt{regular$(L, Q, S, M, Q0, F)$}\index{\texttt{regular/6}}:  Given a finite automaton (DFA or NFA) of $Q$ states numbered 1, 2, $\ldots$, $Q$ with input $1..S$, transition matrix $M$, initial state $Q0$ (1 $\le\ Q0\ \le Q$), and a list of accepting states $F$, this constraint is true if the list $L$ is accepted by the automaton. The transition matrix $M$ represents a mapping from $1..Q\times 1..S$ to $0..Q$, where $0$ denotes the {\it error} state.  For a DFA, every entry in $M$ is an integer, and for an NFA, entries can be a list of integers.

\item \texttt{scalar\_product($A$,$X$,$Product$)}\index{\texttt{scalar\_product/3}}: The scalar product of $A$ and $X$ is $Product$, where $A$ and $X$ are lists or arrays of integer-domain variables, and $Product$ is an integer-domain variable. $A$ and $X$ must have the same length.

\item \texttt{scalar\_product($A$,$X$,$Rel$,$Product$)}\index{\texttt{scalar\_product/4}}: The scalar product of $A$ and $X$ has the relation $Rel$ with $Product$, where $Rel$ is one of the following operators: \verb+#=+, \verb+#!=+, \verb+#>=+, \verb+#>+, \verb+#=<+ (\verb+#<=+), and \verb+#<+. 

\item \texttt{scc($Vs$,$Es$)}\index{\texttt{scc/2}}: This constraint ensures that the \textit{undirected}\index{undirected graph} graph represented by $Vs$ and $Es$ is strongly connected, where $Vs$ is a list of pairs of the form $\{V,B\}$, and $Es$ is a list of triplets of the form $\{V_1,V_2,B\}$. A pair $\{V,B\}$ in $Vs$, where $V$ is a ground term and $B$ is a Boolean variable, denotes that $V$ is in the graph if and only if $B = 1$. A triplet $\{V_1,V_2,B\}$ denotes that $V_1$ is connected with $V_2$  by an edge in the graph if and only if $B = 1$ and both $V_1$ and $V_2$ are in the graph. Note that the graph to be constructed is assumed to be undirected. If there exists a triplet $\{V_1,V_2,B\}$ in $Es$, then the triplet $\{V_2,V_1,B\}$ will be added to $Es$ if it is not specified.

\item \texttt{scc($Vs$,$Es$,$K$)}\index{\texttt{scc/3}}:  This constraint is the same as \texttt{scc($Vs$,$Es$)}, except that it also constrains the number of vertices in the graph to be $K$. 

\item \texttt{scc\_grid($A$)}\index{\texttt{scc\_grid/1}}:  This constraint ensures that the grid\index{grid graph} graph represented by $A$, which is a two-dimensional array of Boolean variables, forms a strongly connected undirected graph. In a grid graph, each cell is directly connected horizontally and vertically, but not diagonally, to its neighbors. Only cells labeled 1 are considered as vertices of the graph. This constraint is implemented as follows by using \texttt{scc}:
\begin{verbatim}
    scc_grid(A) =>
        NRows = len(A),
        NCols = len(A[1]),
        Vs = [{(R,C), A[R,C]} : 
                    R in 1..NRows, 
                    C in 1..NCols],
        Es = [{(R,C), (R1,C1), _} : 
                    R in 1..NRows, 
                    C in 1..NCols,
                    (R1,C1) in neibs(A,NRows,NCols,R,C),
                    (R,C) @< (R1,C1)],
        scc(Vs,Es).

    neibs(A,NRows,NCols,R,C) = 
        [(R1,C1) : (R1,C1) in [(R-1,C), (R+1,C), 
                               (R,C-1), (R,C+1)],
                    R1 >= 1, R1 =< NRows,
                    C1 >= 1, C1 =< NCols, 
                    A[R1,C1] !== 0].
\end{verbatim}
Note that there is an edge between each pair of neighboring cells in the resulting graph as long as the cells are in the graph.

\item \texttt{scc\_grid($A$,$K$)}\index{\texttt{scc\_grid/2}}: This constraint is the same as \texttt{scc\_grid($A$,$Es$)}, except that it also constrains the number of vertices in the graph to be $K$. 

\item \texttt{scc\_d($Vs$,$Es$)}\index{\texttt{scc\_d/2}}: This constraint ensures that the \textit{directed}\index{directed graph} graph represented by $Vs$ and $Es$ is strongly connected, where $Vs$ and $Es$ are the same as those in \texttt{scc($Vs$,$Es$)}, except that the graph is directed.

\item \texttt{scc\_d($Vs$,$Es$,$K$)}\index{\texttt{scc\_d/3}}: This constraint is the same as \texttt{scc\_d($Vs$,$Es$)}, except that it also constrains the number of vertices in the graph to be $K$. 

\item \texttt{serialized($Starts$,$Durations$)}\index{\texttt{serialized/2}}: This constraint describes a set of non-overlapping tasks, where $Starts$ and $Durations$ are lists of integer-domain variables, and the lists have the same length. Let $Os$ be a list of 1s that has the same length as $Starts$. This constraint is equivalent to \texttt{cumulative($Starts$,$Durations$,$Os$,1)}\index{\texttt{cumulative/4}}.

\item \texttt{subcircuit($FDVars$)}\index{\texttt{subcircuit/1}}: This constraint is the same as \texttt{circuit($FDVars$)}\index{\texttt{circuit/1}}, except that not all of the vertices are required to be in the circuit. If the $i$th element of $FDVars$ is $i$, then the vertex $i$ is not part of the circuit. 

\item \texttt{subcircuit\_grid($A$)}\index{\texttt{subcircuit\_grid/1}}: This constraint ensures that the grid\index{grid graph} graph represented by $A$, which is a two-dimensional array of Boolean (0/1) variables, forms a Hamiltonian cycle\index{Hamiltonian cycle}. In a grid graph, each cell is directly connected horizontally and vertically, but not diagonally, to its neighbors. Only non-zero cells are considered as vertices of the graph.

\item \texttt{subcircuit\_grid($A$,$K$)}\index{\texttt{subcircuit\_grid/2}}: This constraint is the same as \\\texttt{subcircuit\_grid($A$)}, except that it also constrains the number of vertices in the graph to be $K$, 

\item \texttt{tree($Vs$,$Es$)}\index{\texttt{tree/2}}: This constraint ensures that the \textit{undirected}\index{undirected graph} graph represented by $Vs$ and $Es$ is a tree, where $Vs$ is a list of pairs of the form $\{V,B\}$, and $Es$ is a list of triplets of the form $\{V_1,V_2,B\}$. A pair $\{V,B\}$ in $Vs$, where $V$ is a ground term and $B$ is a Boolean variable, denotes that $V$ is in the tree if and only if $B = 1$. A triplet $\{V_1,V_2,B\}$ denotes that $V_1$ is connected with $V_2$  by an edge in the tree if and only if $B = 1$ and both $V_1$ and $V_2$ are in the tree. Note that the graph to be constructed is assumed to be undirected. If there exists a triplet $\{V_1,V_2,B\}$ in $Es$, then the triplet $\{V_2,V_1,B\}$ will be added to $Es$ if it is not specified.

\item \texttt{tree($Vs$,$Es$,$K$)}\index{\texttt{tree/3}}:  This constraint is the same as \texttt{tree($Vs$,$Es$)}, except that it also constrains the number of vertices in the tree to be $K$. 
\end{itemize}

\section{Bit-Vector Constraints (sat only)}
The \texttt{sat} module supports bit-vector constraints, which enhance modeling capabilities, improve solving performance, and support large integers that exceed the bounds of domain values. A bit vector is an array representing the binary form of an unsigned integer. Let $V$ be a bit vector of length $N$. The bit $V[1]$ corresponds to the least significant bit, while $V[N]$ represents the most significant bit. In a bit-vector constraint, a bit-vector argument may also be a non-negative integer. If the argument is a non-negative integer, Picat automatically converts it to its binary representation. 

\begin{itemize}
\item \texttt{bv\_add($A$,$B$,$C$)}\index{\texttt{bv\_add/3}}: Forces bit-vector $C$ to be the sum of bit-vectors $A$ and $B$.
\item \texttt{bv\_and($A$,$B$,$C$)}\index{\texttt{bv\_and/3}}: Forces bit-vector $C$ to be the bitwise \textit{and} of bit-vectors $A$ and $B$.
\item \texttt{bv\_div($A$,$B$,$C$)}\index{\texttt{bv\_div/3}}: Forces bit-vector $C$ to be the quotient of $A$ divided by $B$ ($C\ =\ A\ div\ B$).
\item \texttt{bv\_drop($A$,$N$)}\index{\texttt{bv\_drop/2}}: Returns a bit vector containing the remaining bits of bit-vector $A$ after dropping the lowest $N$ bits.
\item \texttt{bv\_eq($A$,$B$)}\index{\texttt{bv\_eq/2}}: Forces equality between bit-vector $A$ and bit-vector $B$.
\item \texttt{bv\_ge($A$,$B$)}\index{\texttt{bv\_ge/2}}: Forces bit-vector $A$ to be greater than or equal to bit-vector $B$ ($A\ \ge\ B$).
\item \texttt{bv\_gt($A$,$B$)}\index{\texttt{bv\_gt/2}}: Forces bit-vector $A$ to be greater than bit-vector $B$ ($A\ >\ B$).
\item \texttt{bv\_mod($A$,$B$,$C$)}\index{\texttt{bv\_mod/3}}: Forces bit-vector $C$ to be the remainder of $A$ divided by $B$ ($C\ =\ A\ mod\ B$).
\item \texttt{bv\_mul($A$,$B$,$C$)}\index{\texttt{bv\_mul/3}}: Forces bit-vector $C$ to be the product of multiplying $A$ and $B$.
\item \texttt{bv\_neq($A$,$B$)}\index{\texttt{bv\_neq/2}}: Forces inequality between bit-vector $A$ and bit-vector $B$ ($A\ \neq\ B$).
\item \texttt{bv\_or($A$,$B$,$C$)}\index{\texttt{bv\_or/3}}: Forces bit-vector $C$ to be the bitwise \textit{or} of bit-vectors $A$ and $B$.
\item \texttt{bv\_pow($A$,$B$,$C$)}\index{\texttt{bv\_pow/3}}: Forces bit-vector $C$ to be $A$ raised to the power of $B$ ($C\ =\ A^B$).
\item \texttt{bv\_sum($As$,$B$)}\index{\texttt{bv\_sum/2}}: Forces the sum of bit-vectors in $As$ to be equal to bit-vector $B$, where $As$ is a list of bit vectors.
\item \texttt{bv\_take($A$,$N$)}\index{\texttt{bv\_take/2}}: Returns a bit vector containing the lowest $N$ bits of bit-vector $A$.
\item \texttt{bv\_to\_int($A$)}\index{\texttt{bv\_to\_int/1}}: Returns an integer represented by bit-vector $A$. This function throws an exception if $A$ is not ground.
\item \texttt{bv\_xor($A$,$B$,$C$)}\index{\texttt{bv\_xor/3}}: Forces bit-vector $C$ to be the bitwise \textit{xor} of bit-vectors $A$ and $B$.
\item \texttt{int\_to\_bv($C$)}\index{\texttt{int\_to\_bv/1}}: Returns the binary representation of integer $C$ as a bit vector.
\item \texttt{new\_bv($N$)}\index{\texttt{new\_bv/1}}: Returns a bit vector of length $N$.
\end{itemize}

\section{Solver Invocation}
\begin{itemize}
\item \texttt{solve($Opts$,$Vars$)}\index{\texttt{solve/2}}: This predicate calls the imported solver to label the variables $Vars$ with values, where $Opts$ is a list of options for the solver. The options will be detailed below. This predicate can backtrack in order to find multiple solutions. The \texttt{cp} module allows \textit{incremental labeling} of variables, and some variables that occur in constraints but are not passed to \texttt{solve} may remain uninstantiated after a call to \texttt{solve}. The user is responsible for having all the variables that need to be instantiated passed to \texttt{solve}. In constrast, the \texttt{sat} and \texttt{mip} modules do not support incremental labeling of variables.

\item\texttt{solve($Vars$)}\index{\texttt{solve/1}}: This predicate is the same as \texttt{solve([],$Vars$)}\index{\texttt{solve/2}}. 
\item \texttt{indomain($Var$)}\index{\texttt{indomain/1}}: This predicate is only accepted by \texttt{cp}. It is the same as \texttt{solve([], [$Var$])}\index{\texttt{solve/2}}.
\item \texttt{solve\_all($Opts$,$Vars$) = $Solutions$}\index{\texttt{solve\_all/2}}: This function returns all the solutions that satisfy the constraints.
\item \texttt{solve\_all($Vars$) = $Solutions$}\index{\texttt{solve\_all/1}}: This function is the same as \texttt{solve\_all([],$Vars$)}.
\item \texttt{solve\_suspended($Opts$)}\index{\texttt{solve\_suspended/1}}: After \texttt{solve($Vars$)} has successfully labeled $Vars$, some constraints may remain suspended and not completely checked because not all of the decision variables are included in $Vars$. The \texttt{solve\_suspended($Opts$)} predicate labels all remaining variables in the suspended constraints. This predicate is only provided by the \texttt{cp} module. 
\item \texttt{solve\_suspended}\index{\texttt{solve\_suspended/0}}: This predicate is the same as \texttt{solve\_suspended([])}.
\item \texttt{indomain\_down($Var$)}\index{\texttt{indomain\_down/1}}: This predicate is the same as \texttt{solve([down], [$Var$])}\index{\texttt{solve/2}}. It is only accepted by \texttt{cp}. 
\end{itemize}


\subsection{Common Solving Options}
The following options are accepted by all four of the solvers.\footnote{Note that the preceding dollar sign indicates that it is followed by a term, not a function call.}
\begin{itemize}
\item \texttt{\$limit($N$)}: Search up to $N$ solutions.
\item \texttt{\$max($Var$)}: Maximize the variable $Var$.
\item \texttt{\$min($Var$)}: Minimize the variable $Var$.
\item \texttt{\$report($Call$)}: Execute $Call$ each time a better answer is found while searching for an optimal answer. This option cannot be used if the {\tt mip} module is used.
\end{itemize}

\subsection{Solving Options for \texttt{cp}}
The \texttt{cp} module also accepts the following options:
\begin{itemize}
\item \texttt{backward}: The list of variables is reversed first.
\item \texttt{constr}: Variables are first ordered by the number of attached constraints.
\item \texttt{degree}: Variables are first ordered by degree, i.e., the number of connected variables.
\item \texttt{down}: Values are assigned to variables from the largest to the smallest.
\item \texttt{ff}: The first-fail principle\index{first-fail principle} is used: the leftmost variable with the smallest domain is selected.
\item \texttt{ffc}: The same as with the two options: \texttt{ff} and \texttt{constr}.
\item \texttt{ffd}: The same as with the two options: \texttt{ff} and \texttt{degree}.
\item \texttt{forward}: Choose variables in the given order, from left to right.
\item \texttt{inout}: The variables are reordered in an inside-out fashion. For example, the variable list \texttt{[X1,X2,X3,X4,X5]} is rearranged into the list \texttt{[X3,X2,X4,X1,X5]}.
\item \texttt{label($CallName$)}: This option informs the CP solver that once a variable $V$ is selected, the user-defined call \texttt{$CallName$($V$)} is used to label $V$, where $CallName$ must be defined in the same module, an imported module, or the global module.
\item \texttt{leftmost}: The same as \texttt{forward}.
\item \texttt{max}: First, select a variable whose domain has the largest upper bound, breaking ties by selecting a variable with the smallest domain.
\item \texttt{min}: First, select a variable whose domain has the smallest lower bound, breaking ties by selecting a variable with the smallest domain.
\item \texttt{rand}: Both variables and values are randomly selected when labeling.
\item \texttt{rand\_var}: Variables are randomly selected when labeling.
\item \texttt{rand\_val}: Values are randomly selected when labeling.
\item \texttt{reverse\_split}: Bisect the variable's domain, excluding the lower half first.
\item \texttt{split}: Bisect the variable's domain, excluding the upper half first.
\item \texttt{updown}: Values are assigned to variables from the values that are nearest to the middle of the domain.
\end{itemize}

\subsection{Solving Options for \texttt{sat}}
\begin{itemize}
\item \texttt{dump}: Dump the CNF code to \texttt{stdout}.
\item \texttt{dump($File$)}: Dump the CNF code to $File$.
\item \texttt{seq}: Use sequential search to find an optimal answer.
\item \texttt{split}: Use binary search to find an optimal answer (default).
\item \texttt{\$nvars$(NVars)$}: The number of variables in the CNF code is $NVars$.
\item \texttt{\$ncls$(NCls)$}: The number of clauses in the CNF code is $NCls$.
%\item \texttt{\$threads($N$)}: Use $N$ threads to solve the generated CNF code. In the current implementation, the parallel version of lingeling, \texttt{plingeling}, will be used if this option is given.\index{parallel}\index{threads}
%\item \texttt{threads}: The same as \texttt{\$threads(8)}.
\end{itemize}

\subsection{Solving Options for \texttt{mip}}
\begin{itemize}
\item \texttt{cbc}: \index{\texttt{cbc}}Instruct Picat to use the Cbc MIP solver. Picat uses the following command to call the Cbc solver:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{cbc $TmpFile$ solve -solu $SolFile$ }
\end{tabbing}
where $SolFile$ is a file for the solution, and $TmpFile$ is a file that stores the CPLEX-format constraints. Picat throws \texttt{existence\_error} if the command \texttt{cbc} is not available.
\item \texttt{dump}: Dump the constraints in CPLEX format to \texttt{stdout}.
\item \texttt{dump($File$)}: Dump the CPLEX format to $File$.
\item \texttt{glpk}: \index{\texttt{glpk}}Instruct Picat to use the GLPK MIP solver. Picat uses the following command to call the GLPK solver:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{glpsol --lp -o $SolFile$ $TmpFile$}
\end{tabbing}
where $SolFile$ is a solution file, and $TmpFile$ is a file that stores the CPLEX-format constraints. Picat throws \texttt{existence\_error} if the command \texttt{glpsol} is not available.
\item \texttt{gurobi}: \index{\texttt{gurobi}}Instruct Picat to use the Gurobi MIP solver. Picat uses the following command to call the Gurobi solver:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{gurobi\_cl ResultFile=$SolFile$ $TmpFile$}
\end{tabbing}
where $SolFile$ is a file for the solution, and $TmpFile$ is a file that stores the CPLEX-format constraints. Picat throws \texttt{existence\_error} if the command \texttt{gurobi\_cl} is not available.
% \item \texttt{sol($File$)}: Instruct the mip solver to save the solution into $File$ rather than the default file ``\_\_tmp.sol''.
\item \texttt{scip}: \index{\texttt{scip}}Instruct Picat to use the SCIP MIP solver. Picat provides an internal interface to the SCIP solver through the C language.\footnote{The SCIP interface is not included in the pre-made binary executables, and users must build an executable from the source code following the installation instructions.} Note that, unlike other linear programming solvers, SCIP only returns integer solutions although it allows real coefficients and contiguous-domain variables.
\end{itemize}

\subsection{Solving Options for \texttt{smt}}
\begin{itemize}
\item \texttt{cvc4}: \index{\texttt{cvc3}}Instruct Picat to use the CVC4 SMT solver. Picat uses the following command to call the CVC4 solver:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{cvc4 $TmpFile$ $>$ $SolFile$ }
\end{tabbing}
where $TmpFile$ is a file that stores the SMT-LIB2-format constraints, and $SolFile$ is a solution file. Picat throws \texttt{existence\_error} if the command \texttt{cvc4} is not available in the path.
\item \texttt{dump}: Dump the constraints in SMT-LIB2 format to \texttt{stdout}.
\item \texttt{dump($File$)}: Dump the SMT-LIB2 format to $File$.
\item \texttt{logic($Logic$)}: Instruct the SMT solver to use $Logic$ in the solving, where $Logic$ must be an atom or a string, and the specified logic must be available in the SMT solver. The default logic for Z3 is ``LIA'', and the default logic for CVC4 is ``NIA''.
\item \texttt{tmp($File$)}: Dump the SMT-LIB2 format to $File$ rather than the default file ``\_\_tmp.smt2'', before calling the smt solver. The name $File$  must be a string or an atom that has the extension name ``.smt2''. When this file name is specified, the smt solver will save the solution into a file name that has the same main name as $File$ but the extension name ``.sol''.
\item \texttt{z3}: \index{\texttt{z3}}Instruct Picat to use the z3 SMT solver. When no SMT solver is specified, Picat first searches for the command \texttt{z3}, and when \texttt{z3} cannot be found it continues to search for the command \texttt{cvc4}.
\end{itemize}
\ignore{
\end{document}
}
\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:nn}The \texttt{nn} (Neural Networks) Module}

The \texttt{nn} module provides a high-level interface between Picat and the FANN\footnote{\url{http://leenissen.dk/fann/wp/}} neural networks library, which implements feedforward neural networks.\footnote{The Picat-FANN interface was implemented by Sanders Hernandez.}\index{neural network}\index{feedforward neural network}  A \emph{feedforward neural network} consists of \emph{neurons} organized in layers from an input layer to an output layer, possibly with a number of hidden layers. A feedforward network represents a function from input to output. Neurons in a layer (except for the input layer) are connected to neurons in the previous layer. The connections have weights.  The neurons in the input layer receive the input. The information is propagated forward through the layers until it reaches the output layer, where the output is returned. The information that a neuron receives is determined by the connected predecessor neurons, the weights of the connections, and an \emph{activation function}.\index{activation function} The connection weights of a neural network are normally adjusted through training on a given set of input-output pairs, called \emph{training data}. Once a neural network is trained, it can be used to predict the output for a given input.

The following gives an example program which creates a neural network for the \texttt{xor} function,  and trains it on a set of data stored in a file:
\begin{verbatim}
import nn.

main =>
    NN = new_nn({2,3,1}),
    nn_train(NN,"xor.data"),
    nn_save(NN,"xor.net"),
    nn_destroy_all.
\end{verbatim}
The function \texttt{new\_nn(\{2,3,1\})} returns a neural network with three layers, where the input layer has 2 neurons, the hidden layer has 3 neurons, and the output layer has 1 neuron. The program does not specify any activation functions used between layers, entailing that the default activation function, which is \texttt{sym\_sigmoid}, will be used. The predicate \texttt{nn\_train(NN,"xor.data")} trains the neural network with the training data stored in the file \texttt{"xor.data"}. The user is able to specify an algorithm to be used in the training and several parameters that affect the behavior of the algorithm, such as the maximum number of iterations (called \textit{epochs}), the learning rate, and the error function. This example does not specify a training algorithm or any of the training parameters, entailing that the default algorithm, which is \texttt{rprop}, is used with the default setting. The predicate \texttt{nn\_save} saves the trained neural network into a file named \texttt{"xor.net"}. The predicate \texttt{nn\_destroy\_all} clears the neural network and the internal data structures used during training.

The text file \texttt{"xor.data"} contains the following training data:
\begin{verbatim}
4 2 1
-1 -1
-1
-1 1
1
1 -1
1
1 1
-1
\end{verbatim}
The three integers in the first line state, respectively, that the number of input-output pairs is 4, the number of input values is 2, and the number of output values is 1. The remaining lines give the input-output pairs. 

The following program performs the same task as the above program, except that it trains the neural network with internal data:
\begin{verbatim}
import nn.

main =>
    NN = new_nn({2,3,1}),
    nn_train(NN,[({-1,-1}, -1), 
                 ({-1,1}, 1), 
                 ({1,-1}, 1), 
                 ({1,1}, -1)]),
    nn_save(NN,"xor.net"),
    nn_destroy_all.
\end{verbatim}
The predicate \texttt{nn\_train} is overloaded. When the second argument is a file name, Picat reads training data from the file. Otherwise, Picat expects a collection (a list or an array) of input-output pairs.

The following example program illustrates how to use a trained network:
\begin{verbatim}
import nn.

main =>
    NN = nn_load("xor.net"),
    printf("xor(-1,1) = %w\n",nn_run(NN,{-1,1})),
    nn_destroy_all.
\end{verbatim}
The function \texttt{nn\_load} loads a neural network. The function \texttt{nn\_run} uses the network to predict the output for an input.

\section{Create, Print, and Destroy Neural Networks}
\begin{itemize}
\item \texttt{new\_nn($Layers$) = $NN$}\index{\texttt{new\_nn/1}}: This function creates a fully-connected neural network of the structure $Layers$, which is a collection of positive integers indicating the number of neurons in each layer.

\item \texttt{new\_standard\_nn($Layers$) = $NN$}\index{\texttt{new\_standard\_nn/1}}: This function is the same as \texttt{new\_nn($Layers$)}.

\item \texttt{new\_sparse\_nn($Layers$,$Rate$) = $NN$}\index{\texttt{new\_sparse\_nn/2}}: This function creates a sparse neural network that has the structure $Layers$ and the connection rate $Rate$. The connection rate determines the sparseness of the network, with 1 indicating that the network is fully connected, and 0 indicating that the network is not connected at all.

\item \texttt{new\_sparse\_nn($Layers$) = $NN$}\index{\texttt{new\_sparse\_nn/1}}: This function is the same as \texttt{new\_sparse\_nn($Layers$, 0.5)}.

\item \texttt{nn\_print($NN$)}\index{\texttt{nn\_print/1}}: This predicate prints the attributes of the neural network $NN$, including the connections, the weights, the activation functions, and some other parameters.

\item \texttt{nn\_destroy($NN$)}\index{\texttt{nn\_destroy/1}}: This predicate destroys the neural network $NN$.

\item \texttt{nn\_destroy\_all}\index{\texttt{nn\_destroy\_all/0}}: This predicate destroys all the neural networks and the internal data structures.
\end{itemize}

\section{Activation Functions}
An activation function for a neuron determines how information is propagated to it from its predecessor neurons. When a new neural network is created, it uses the default activation function \texttt{sym\_sigmoid} for all of its non-input neurons. The following predicates can be utilized to set activation functions.

\begin{itemize}
\item \texttt{nn\_set\_activation\_function\_layer($NN$,$Func$,$Layer$)}\index{\texttt{nn\_set\_activation\_.../3}}: This predicate sets the activation function to $Func$ for all the neurons in layer $Layer$ in the neural network $NN$. Let the number of layers in $NN$ be $n$. Since the first layer is numbered 1, $Layer$ must satisfy $2\ \le\ Layer\ \le n$. The following activation functions are available:
\begin{itemize}
\item \texttt{linear}
\item \texttt{threshold}
\item \texttt{sym\_threshold}: symmetric threshold.
\item \texttt{sigmoid}
\item \texttt{step\_sigmoid}: stepped sigmoid
\item \texttt{sym\_sigmoid}: symmetric sigmoid
\item \texttt{elliot}: an alternative for sigmoid
\item \texttt{sym\_elliot}: symmetric elliot
\item \texttt{gaussian}
\item \texttt{sym\_gaussian}: symmetric Gaussian
\item \texttt{linear\_piece}
\item \texttt{sym\_linear\_piece}: symmetric linear piece
\item \texttt{sin}
\item \texttt{sym\_sin}: symmetric sin
\item \texttt{cos}
\item \texttt{sym\_cos}: symmetric cos
\end{itemize}
The detault activation function is \texttt{sym\_sigmoid}. Each of these functions has a corresponding name in FANN. Please refer to the FANN documentation for a more detailed description of these functions.

\item \texttt{nn\_set\_activation\_function\_hidden($NN$,$Func$)}\index{\texttt{nn\_set\_activation\_.../2}}: This predicate sets the activation function to $Func$ for all of the hidden layers in the neural network $NN$.

\item \texttt{nn\_set\_activation\_function\_output($NN$,$Func$)}\index{\texttt{nn\_set\_activation\_.../2}}: This predicate sets the activation function to $Func$ for the output layer in the neural network $NN$.

\item \texttt{nn\_set\_activation\_steepness\_layer($NN$,$Steepness$,$Layer$)}\index{\texttt{nn\_set\_activation\_.../3}}: This predicate sets the activation steepness for all of the neurons in $Layer$, where $-1\ \le\ Steepness\ \le 1$ and $2 \le Layer\ \le n$ ($n$ is the number of layers in $NN$).  A high steepness value means a more aggressive training. The default steepness is 0.5.

\item \texttt{nn\_set\_activation\_steepness\_hidden($NN$,$Steepness$)}\index{\texttt{nn\_set\_activation\_.../2}}: This predicate sets the activation steepness to $Steepness$ for all of the hidden layers in the neural network $NN$.

\item \texttt{nn\_set\_activation\_steepness\_output($NN$,$Steepness$)}\index{\texttt{nn\_set\_activation\_.../2}}: This predicate sets the activation steepness to $Steepness$ for the output layer in the neural network $NN$.
\end{itemize}

\section{Training Data}
A training dataset can be supplied to FANN either through a text file or a Picat collection. A training dataset file must have the following format:

\begin{verbatim}
num_train_data num_input num_output
input_data separated by space
output_data separated by space
.
.
.
input_data separated by space
output_data separated by space
\end{verbatim}
A training dataset stored in a Picat collection must be either a list or an array of input-output pairs. An input-output pair has the form \texttt{($Input$,$Output$)}, where $Input$ is an array of numbers or a single number, and so is $Output$.

\begin{itemize}
\item \texttt{nn\_train\_data\_size($Data$) = $Size$}\index{\texttt{nn\_train\_data\_size/1}}: This function returns the number of input-output pairs in the dataset $Data$, which is either a file name or a Picat collection.

\item \texttt{nn\_train\_data\_get($Data$,$I$) = $Pair$}\index{\texttt{nn\_train\_data\_get/2}}: This function returns the $I$th pair in the dataset $Data$. Notice that while this function takes linear time when $Data$ is a list, it takes constant time when $Data$ is a file name or an array.\footnote{The data is loaded into an internal array when the dataset is accessed the first time.}

\item \texttt{nn\_train\_data\_load($File$) = $Data$}\index{\texttt{nn\_train\_data\_load/1}}: This function loads a dataset stored in $File$ into a Picat array, and returns the array.

\item \texttt{nn\_train\_data\_save($Data$,$File$)}\index{\texttt{nn\_train\_data\_save/2}}: This predicate saves a dataset in a Picat collection $Data$ into a file named $File$.
\end{itemize}

\section{Train Neural Networks}
\begin{itemize}
\item \texttt{nn\_train($NN$,$Data$,$Opts$)}\index{\texttt{nn\_train/3}}: This predicate trains the neural network $NN$ using the dataset $Data$ under the control of training options $Opts$. The following training options are supported:
\begin{itemize}
\item \texttt{maxep($X$)}: $X$ is the maximum number of epochs for training.
\item \texttt{report($X$)}:	reporting every $X$ number of epochs. 
\item \texttt{derror($X$)}:	$X$ is the desired error in training.
\item \texttt{train\_func($X$)}: $X$ is the training algorithm to be used, which is one of the following: \texttt{batch}, \texttt{inc}, \texttt{qprop} (quick prop), \texttt{rprop}, and \texttt{sprop} (sarprop).
\item \texttt{lrate($X$)}: $X$ is the learning rate.
\item \texttt{momentum($X$)}: $X$ is the learning momentum.
\item \texttt{error\_func($X$)}: $X$ is the error function to be used, which is either \texttt{linear} or \texttt{tanh}.
\item \texttt{stop\_func($X$)}:	$X$ is the stop function to be used, which is either \texttt{bit} or \texttt{mse}.
\item \texttt{bfl($X$)}:  $X$ is the bit fail limit.
\item \texttt{qp\_decay($X$)}:	 $X$ is the \texttt{qprop} decay.
\item \texttt{qp\_mu($X$)} : $X$ is \texttt{qprop}  mu factor.
\item \texttt{rp\_increase($X$)}:	$X$ is the \texttt{rprop} increase factor.
\item \texttt{rp\_decrease($X$)}: $X$ is the \texttt{rprop} decrease factor.
\item \texttt{rp\_deltamin($X$)}: $X$ is the \texttt{rprop} delta min.
\item \texttt{rp\_deltamax($X$)}: $X$ is the \texttt{rprop} delta max.
\item \texttt{rp\_deltazero($X$)}: $X$ is the \texttt{rprop} delta zero.
\item \texttt{sp\_weight($X$)}:	$X$ is the \texttt{sarprop} weight decay.
\item \texttt{sp\_thresh($X$)}: $X$ is the \texttt{sarprop} step error threshold factor.
\item \texttt{sp\_shift($X$)}: $X$ is the \texttt{sarprop} step error shift.
\item \texttt{sp\_temp($X$)}: $X$ is the \texttt{sarprop} temperature.
\item \texttt{scale($InMin$,$InMax$,$OutMin$,$OutMax$)}: use training data scaling.
\item \texttt{inscale($InMin$,$InMax$)}:  use input data scaling.
\item \texttt{outscale($OutMin$,$OutMax$)}: use output data scaling.
\end{itemize}

\item \texttt{nn\_train($NN$,$Data$)}\index{\texttt{nn\_train/2}}: This predicate is the same as \texttt{nn\_train($NN$,$Data$,[])}.
\end{itemize}

\section{Save and Load Neural Networks}
\begin{itemize}
\item \texttt{nn\_save($NN$,$File$)}\index{\texttt{nn\_save/2}}: This predicate saves the neural network $NN$ to a file named $File$.

\item \texttt{nn\_load($File$) = $NN$}\index{\texttt{nn\_load/1}}: This function creates a neural network from a FANN neural network file named $File$.
\end{itemize}

\section{Run Neural Networks}
\begin{itemize}
\item \texttt{nn\_run($NN$,$Input$,$Opts$) = $Output$}\index{\texttt{nn\_run/3}}: This function predicts the output of a given input using the trained neural network $NN$, where $Input$ is an array of numbers or a single number, and $Opts$ is a list of testing options. The supported testing options include:
\begin{itemize}
\item \texttt{scaleIn($X$)}: $X$ indicates whether or not the input is scaled, with -1 meaning descale, 1 meaning scale, and 0 meaning nothing.
\item \texttt{scaleOut($X$)}: $X$ indicates whether or not the output is scaled,  with -1 meaning descale, 1 meaning scale, and 0 meaning nothing.	
\item \texttt{resetMSE}: resets the current mean squared error of the network.
\end{itemize}

\item \texttt{nn\_run($NN$,$Input$) = $Output$}\index{\texttt{nn\_run/2}}: This function is the same as \texttt{nn\_run($NN$,$Input$,[])}.
\end{itemize}

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

\makeindex
\begin{document}

}
\chapter{The \texttt{os} Module}
Picat has an \texttt{os} module for manipulating files and directories.  In order to use any of the functions or predicates, users must import the module.

\section{The $Path$ Parameter}
Many of the functions and predicates in this module have a $Path$ parameter.  This parameter is a string or an atom, representing the path of a file or directory.  This path can be an absolute path, from the system's root directory, or a relative path, from the current file location.  Different systems use different separator characters to separate directories in different levels of the directory hierarchy.  For example, Windows uses `\texttt{$\backslash$}' and Unix uses `\texttt{/}'.  The following function outputs a single character, representing the character that the current system uses as a file separator.
\begin{itemize}
\item \texttt{separator() = $Val$}\index{\texttt{separator/0}}
\end{itemize}

\section{Directories}
The \texttt{os} module includes functions for reading and modifying directories.  The following example shows how to list all of the files in a directory tree, using a depth-first directory traversal.

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

traverse(Dir), directory(Dir) =>
   List = listdir(Dir),
   printf("Inside %s%n",Dir),
   foreach (File in List)
       printf("    %s%n",File)
   end,
   foreach (File in List, File != ".", File != "..")
       FullName = Dir ++ [separator()] ++ File,
       traverse(FullName) 
   end.
traverse(_Dir) => true.
\end{verbatim}

The following function can be used to read the contents of a directory:
\begin{itemize}
\item \texttt{listdir($Path$) = $List$}\index{\texttt{listdir/1}}: This function returns a list of all of the files and directories that are contained inside the directory specified by $Path$.  If $Path$ is not a directory, then an error is thrown.  The returned list contains strings, each of which is the name of a file or directory.
\ignore{
\item \texttt{listdir($Path$,$Pattern$) = $List$}\index{\texttt{listdir/2}}: The $Pattern$ parameter is a string that represents a regular expression.  The list that is returned will only contain files and directories whose names match the regular expression.
\item \texttt{root() = $Path$}\index{\texttt{root/0}}: This function returns a string representing the path of the root of the file system tree (such as ``C:$\backslash$", or ``/").
}
\end{itemize}
The above example also uses the \texttt{directory}\index{\texttt{directory/1}} predicate, which will be discussed in Section \ref{file_info}.

\subsection{The Current Working Directory}
The \texttt{os} module includes two functions that obtain the program's current working directory:
\begin{itemize}
\item \texttt{cwd() = $Path$}\index{\texttt{cwd/0}}
\item \texttt{pwd() = $Path$}\index{\texttt{pwd/0}}
\end{itemize}

The \texttt{os} module also includes two predicates to change the program's current working directory:
\begin{itemize}
\item \texttt{cd($Path$)}\index{\texttt{cd/1}}
\item \texttt{chdir($Path$)}\index{\texttt{chdir/1}}
\end{itemize}
If the \texttt{cd}\index{\texttt{cd/1}} and \texttt{chdir}\index{\texttt{chdir/1}} predicates cannot move to the directory specified by $Path$, the functions throw an error.  This can occur if $Path$ does not exist, if $Path$ is not a directory, or if the program does not have permission to access $Path$.

\section{Modifying Files and Directories}
\ignore{
In a file system, each directory entry refers to a structure called an \emph{inode}\index{inode}, which contains file information.  The \texttt{ino}\index{\texttt{ino/1}} function returns the number of the inode\index{inode} to which $Path$ refers.
}

\subsection{Creation}
The \texttt{os} module contains a number of predicates for creating new files and directories:
\begin{itemize}
\ignore{
\item \texttt{create($Path$)}\index{\texttt{create/1}}: This predicate creates a new file at location $Path$.  The file will be created with a default permission list of \texttt{[rwu, rwg, ro]}.  If the program does not have permission to write to the parent directory of $Path$, this predicate will throw an error.  An error will also occur if the parent directory does not exist.  
\item \texttt{create($Path$,$Mode$)}\index{\texttt{create/2}}: The $Mode$ parameter indicates access permissions.  For details, see the \texttt{chmod}\index{\texttt{chmod/2}} function, in Section \ref{modification}.  If a permission is not explicitly specified in the $Mode$ parameter, then the permission is not provided.
}
\item \texttt{mkdir($Path$)}\index{\texttt{mkdir/1}}: This predicate creates a new directory at location $Path$.  The directory will be created with a default permission list of \texttt{[rwu, rwg, ro]}.  If the program does not have permission to write to the parent directory of $Path$, this predicate will throw an error.  An error will also occur if the parent directory does not exist.  

\item \texttt{rename($Old$,$New$)}\index{\texttt{rename/2}}: This renames a file or a directory from $Old$ to $New$.  This predicate will throw an error if $Old$ does not exist.  An error will also occur if the program does not have permission to write to $Old$ or $New$.

\item \texttt{cp($FromPath$,$ToPath$)}\index{\texttt{cp/2}}: This copies a file from $FromPath$ to $ToPath$.  This predicate will throw an error if $FromPath$ does not exist or $FromPath$ is a directory.  An error will also occur if the program does not have permission to read from $FromPath$, or if it does not have permission to write to $ToPath$.

\end{itemize}

\ignore{
\subsection{\label{modification}Modification}
The \texttt{os} module has one predicate for modifying access permissions.
\begin{itemize}
\item \texttt{chmod($Path$,$Mode$)}\index{\texttt{chmod/2}}: An error will be thrown if the program cannot modify the permissions.
\end{itemize}
The $Mode$ parameter is either a single atom or a list of two or three atoms.  This parameter specifies the access permissions.  The format of the atoms is specified by the regular expression \texttt{r?w?x?(u|g|o)}.  If the atom contains \texttt{r}, then it provides permission to read from the file.  If the atom contains \texttt{w}, then it provides permission to write to the file.  If the atom contains \texttt{x}, then it provides permission to execute the file.  The second part of the atom indicates the receiver(s) of the permission, where \texttt{u} specifies the user, \texttt{g} specifies anybody who is in the user's group, and \texttt{o} specifies anybody who is not in the user's group.  At most one atom can exist for each of \texttt{u}, \texttt{g}, and \texttt{o}.  

Note that the \texttt{chmod}\index{\texttt{chmod/2}} predicate will only modify the permissions for the specified receivers.  If a receiver is not specified in the $Mode$ parameter, then the receiver will have the same permissions as the receiver had before \texttt{chmod}\index{\texttt{chmod/2}} was called. 
}

\subsection{Deletion}
The \texttt{os} module contains a number of predicates for deleting files and directories.
\begin{itemize}
\item \texttt{rm($Path$)}\index{\texttt{rm/1}}: This deletes a file.  An error will be thrown if the file does not exist, if the program does not have permission to delete the file, or if $Path$ refers to a directory, a hard link\index{hard link}, a symbolic link\index{symbolic link}, or a special file type.
\item \texttt{rmdir($Path$)}\index{\texttt{rmdir/1}}: This deletes a directory.  An error will be thrown if the directory does not exist, the program does not have permission to delete the directory, the directory is not empty, or if $Path$ does not refer to a directory.
\ignore{
\item \texttt{unlink($Path$)}\index{\texttt{unlink/1}}: This removes a hard link\index{hard link} or a symbolic link\index{symbolic link}.
}
\end{itemize}

\section{\label{file_info}Obtaining Information about Files}
The \texttt{os} module contains a number of functions that retrieve file status information, and predicates that test the type of a file.  These predicates will all throw an error if the program does not have permission to read from $Path$.
\begin{itemize}
\ignore{
\item \texttt{dev\_id($Path$) = $Int$}\index{\texttt{dev\_id/1}}: This function returns the device ID of the device that contains $Path$.
\item \texttt{ino($Path$) = $Int$}\index{\texttt{ino/1}}: This function returns the inode\index{inode} number of $Path$.  
\item \texttt{mode($Path$) = $String$}\index{\texttt{mode/1}}: This function returns the file permissions for $Path$ in a string.  The string will contain atoms, in the same format as the atoms that are passed to the \texttt{chmod}\index{\texttt{chmod/2}} predicate.  This function will throw an error if $Path$ does not exist.
\item \texttt{mode($Path$,$Value$)}\index{\texttt{mode/2}}: Does the program's current permission for the file include $Value$?  The $Value$ parameter is one of the atoms: \texttt{read}, \texttt{write}, or \texttt{execute}.
\item \texttt{nlink($Path$) = $Int$}\index{\texttt{nlink/1}}: This function returns the number of hard links\index{hard link} to the inode\index{inode} to which $Path$ refers.
\item \texttt{uid($Path$) = $Int$}\index{\texttt{uid/1}}: This function returns the user ID of the user who created $Path$.  This function will throw an error if $Path$ does not exist.
\item \texttt{gid($Path$) = $Int$}\index{\texttt{gid/1}}: This function returns the group ID of the user who created $Path$.  This function will throw an error if $Path$ does not exist.
\item \texttt{atime($Path$) = $DateTime$}\index{\texttt{atime/1}}: This function returns the date and time that $Path$ was last accessed.
\item \texttt{ctime($Path$) = $DateTime$}\index{\texttt{ctime/1}}: This function returns the date and time that $Path$ was created.
\item \texttt{mtime($Path$) = $DateTime$}\index{\texttt{mtime/1}}: This function returns the date and time that $Path$ was last modified.
\item \texttt{file\_type($Path$) = $Term$}\index{\texttt{file\_type/1}}: This returns the type of $Path$.  The value returned is one of the atoms: \texttt{regular}, \texttt{directory}, \texttt{hard\_link}, \texttt{symbolic\_link}, \texttt{fifo}, \texttt{socket}, \texttt{block\_special}, \texttt{char\_special}, \texttt{message\_queue}, \texttt{semaphore}, \texttt{shared\_memory}, or \texttt{unknown}.
\item \texttt{link($Path$)}\index{\texttt{link/1}}: Does $Path$ refer to a hard link\index{hard link}?  
\item \texttt{shortcut($Path$)}\index{\texttt{shortcut/1}}: Does $Path$ refer to a symbolic link\index{symbolic link}?  This predicate might not be supported by Windows.
\item \texttt{fifo($Path$)}\index{\texttt{fifo/1}}: Does $Path$ refer to a named pipe\index{fifo}?
\item \texttt{socket($Path$)}\index{\texttt{socket/1}}: Does $Path$ refer to a socket\index{socket}?
\item \texttt{block\_special($Path$)}\index{\texttt{block\_special/1}}: Does $Path$ refer to a block special file?  A \emph{special file} is used to communicate with hardware.  A block special file is capable of reading or writing blocks of data at a time.  This predicate might not be supported by Windows.
\item \texttt{char\_special($Path$)}\index{\texttt{char\_special/1}}: Does $Path$ refer to a character special file?  A character special can only read or write one character at a time.
\item \texttt{message\_queue($Path$)}\index{\texttt{message\_queue/1}}: Does $Path$ refer to a message queue?  Message queues, as defined by POSIX, allow processes to exchange data through messages.  This predicate is true if the system implements POSIX message queues and $Path$ refers to a message queue.
\item \texttt{semaphore($Path$)}\index{\texttt{semaphore/1}}: Does $Path$ refer to a semaphore\index{semaphore}?  Semaphores\index{semaphore} are used to protect critical sections, in which race conditions can occur, in multithreaded code.  This predicate is true $Path$ refers to a semaphore.  For more on semaphores\index{semaphore}, see Chapter \ref{chapter:thread}.
\item \texttt{shared\_memory($Path$)}\index{\texttt{shared\_memory/1}}: Does $Path$ refer to a shared memory object?  Shared memory objects, as defined by POSIX, allow unrelated processes to share an area of memory.  This predicate is true if the system implements POSIX shared memory objects, and $Path$ refers to a shared memory object.
}
\item \texttt{readable($Path$)}\index{\texttt{readable/1}}: Is the program allowed to read from the file?
\item \texttt{writable($Path$)}\index{\texttt{writable/1}}: Is the program allowed to write to the file?
\item \texttt{executable($Path$)}\index{\texttt{executable/1}}: Is the program allowed to execute the file?
\item \texttt{size($Path$) = $Int$}\index{\texttt{size/1}}: If $Path$ is not a symbolic link\index{symbolic link}, then this function returns the number of bytes contained in the file to which $Path$ refers.  If $Path$ is a symbolic link\index{symbolic link}, then this function returns the path size of the symbolic link\index{symbolic link}. Because the function {\tt size/1} is defined in the {\tt basic} module for returning the size of a map, this function requires an explicit module qualifier {\tt os.size($Path$)}.

\item \texttt{file\_base\_name($Path$) = $List$}\index{\texttt{file\_base\_name/1}}: This function returns a string containing the base name of $Path$.  For example, the base name of ``\texttt{a/b/c.txt}" is ``\texttt{c.txt}".
\item \texttt{file\_directory\_name($Path$) = $List$}\index{\texttt{file\_directory\_name/1}}: This function returns a string containing the path of the directory that contains $Path$.  For example, the directory name of ``\texttt{a/b/c.txt}" is ``\texttt{a/b/}".
\item \texttt{exists($Path$)}\index{\texttt{exists/1}}: Is $Path$ an existing file or directory?
\item \texttt{file($Path$)}\index{\texttt{file/1}}: Does $Path$ refer to a regular file?  This predicate is true if $Path$ is neither a directory nor a special file, such as a socket or a pipe.
\item \texttt{file\_exists($Path$)}\index{\texttt{file\_exists/1}}:  This tests whether $Path$ exists, and, if it exists, whether $Path$ refers to a regular file.
\item \texttt{directory($Path$)}\index{\texttt{directory/1}}: Does $Path$ refer to a directory?
\end{itemize}

The following example shows how to use a few of the predicates.

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

test_file(Path) =>
    if (not exists(Path))
        printf("%s does not exist %n",Path)
    elseif (directory(Path))
        println("Directory")
    elseif (file(Path))
        println("File")
    else
        println("Unknown")
    end.
\end{verbatim}

\section{Environment Variables}
\begin{itemize}
\item \texttt{env\_exists($Name$)}\index{\texttt{env\_exists/1}}: This predicate succeeds if $Name$ is an environment variable in the system.
\item \texttt{getenv($Name$) = $String$}\index{\texttt{getenv/1}}: This function returns the value of the environment variable \texttt{$Name$} as a string. This function will throw an error if the environment variable $Name$ does not exist.
\end{itemize}
\ignore{
\end{document}
}
\appendix
\chapter{The \texttt{math} Module}\label{chapter:math}
Picat provides a \texttt{math} module, which has common mathematical constants and functions.  The \texttt{math} module is imported by default.

%In order to use the examples in this chapter, first type \texttt{import math}\index{\texttt{import}} on the command line.

\section{Constants}
The \texttt{math} module provides two constants.
\begin{itemize}
\item \texttt{e = 2.71828182845904523536}\index{\texttt{e}}
\item \texttt{pi = 3.14159265358979323846}\index{\texttt{pi}}
%\item \texttt{inf}\index{\texttt{inf}}: This represents positive infinity.
%\item \texttt{ninf}\index{\texttt{ninf}}: This represents negative infinity.
\end{itemize}

\section{Functions}
The \texttt{math} module contains mathematical functions that serve a number of different purposes.  Note that the arguments must all be numbers.  If the arguments are not numbers, then Picat will throw an error.

\subsection{Sign and Absolute Value}
The following functions deal with the positivity and negativity of numbers.
\begin{itemize}
\item \texttt{sign($X$) = $Val$}\index{\texttt{sign/1}}: This function determines whether $X$ is positive or negative.  If $X$ is positive, then this function returns $1$.  If $X$ is negative, then this function returns $-1$.  If $X$ is $0$, then this function returns $0$.
\item \texttt{abs($X$) = $Val$}\index{\texttt{abs/1}}: This function returns the absolute value of $X$.  If $X \ge 0$, then this function returns $X$.  Otherwise, this function returns $-X$.
\end{itemize}

\subsection*{Example}
\begin{verbatim}
Picat> Val1 = sign(3), Val2 = sign(-3), Val3 = sign(0)
Val1 = 1
Val2 = -1
Val3 = 0
Picat> Val = abs(-3)
Val = 3
\end{verbatim}

\subsection{Rounding and Truncation}
The \texttt{math} module includes the following functions for converting a real number into the integers that are closest to the number.
\begin{itemize}
\item \texttt{ceiling($X$) = $Val$}\index{\texttt{ceiling/1}}: This function returns the closest integer that is greater than or equal to $X$.
\item \texttt{floor($X$) = $Val$}\index{\texttt{floor/1}}: This function returns the closest integer that is less than or equal to $X$.
\item \texttt{round($X$) = $Val$}\index{\texttt{round/1}}: This function returns the integer that is closest to $X$.
\item \texttt{truncate($X$) = $Val$}\index{\texttt{truncate/1}}: This function removes the fractional part from a real number.  
\item \texttt{modf($X$) = ($IntVal$,$FractVal$)}\index{\texttt{modf/1}}: This function splits a real number into its integer part and its fractional part.
\end{itemize}

\subsection*{Example}
\begin{verbatim}
Picat> Val1 = ceiling(-3.2), Val2 = ceiling(3)
Val1 = -3
Val2 = 3
Picat> Val1 = floor(-3.2), Val2 = floor(3)
Val1 = -4
Val2 = 3
Picat> Val1 = round(-3.2), Val2 = round(-3.5), Val3 = round(3.5)
Val1 = -3
Val2 = -4
Val3 = 4
Picat> Val1 = truncate(-3.2), Val2 = truncate(3)
Val1 = -3
Val2 = 3
Picat> IF = modf(3.2)
IF = (3.0 , 0.2)
\end{verbatim}

\subsection{Exponents, Roots, and Logarithms}
The following functions provide exponentiation, root, and logarithmic functions.  Note that, in the logarithmic functions, if $X \le 0$, then an error is thrown.
\begin{itemize}
\item \texttt{pow($X$,$Y$) = $Val$}\index{\texttt{pow/2}}:  This function returns $X^Y$.  It does the same thing as $X ** Y$.
\item \texttt{pow\_mod($X$,$Y$,$Z$) = $Val$}\index{\texttt{pow\_mod/3}}:  This function returns \texttt{$X^Y$ mod $Z$}.  All of the arguments must be integers, and $Y$ must not be negative.
\item \texttt{exp($X$) = $Val$}\index{\texttt{exp/1}}:  This function returns $e^X$.
\item \texttt{sqrt($X$) = $Val$}\index{\texttt{sqrt/1}}: This function returns the square root of $X$.  Note that the \texttt{math} module does not support imaginary numbers.  Therefore, if $X < 0$, this function throws an error.
%\item \texttt{cbrt($X$) = $Val$}\index{\texttt{cbrt/1}}: This function returns the cube root of $X$.
%\item \texttt{nthrt($N$,$X$) = $Val$}\index{\texttt{nthrt/2}}: This function returns the $N$th root of $X$.  Note that, if $N$ is even, and $X < 0$, then this function throws an error. 
\item \texttt{log($X$) = $Val$}\index{\texttt{log/1}}: This function returns $log_e(X)$.
\item \texttt{log10($X$) = $Val$}\index{\texttt{log10/1}}: This function returns $log_{10}(X)$.
\item \texttt{log2($X$) = $Val$}\index{\texttt{log2/1}}: This function returns $log_2(X)$.
\item \texttt{log($B$,$X$) = $Val$}\index{\texttt{log/2}}:  This function returns $log_B(X)$.
\end{itemize}

\subsection*{Example}
\begin{verbatim}
Picat> P1 = pow(2, 5), P2 = exp(2)
P1 = 32
P2 = 7.38906
Picat> S = sqrt(1)
S = 1.0
Picat> E = log(7), T = log10(7), T2 = log2(7), B = log(7, 7)
E = 1.94591
T = 0.845098
T2 = 2.80735
B = 1.0
\end{verbatim}

\subsection{Converting Between Degrees and Radians}
The \texttt{math} module has two functions to convert between degrees and radians.
\begin{itemize}
\item \texttt{to\_radians($Degree$) = $Radian$}\index{\texttt{to\_radians/1}}: This function converts from degrees to radians.
\item \texttt{to\_degrees($Radian$) = $Degree$}\index{\texttt{to\_degrees/1}}: This function converts from radians to degrees.
\end{itemize}

\subsection*{Example}
\begin{verbatim}
Picat> R = to_radians(180)
R = 3.14159
Picat> D = to_degrees(pi)
D = 180.0
\end{verbatim}

\subsection{Trigonometric Functions}
The \texttt{math} module provides the following trigonometric functions.
\begin{itemize}
\item \texttt{sin($X$) = $Val$}\index{\texttt{sin/1}}: This function returns the sine of $X$, where $X$ is given in radians.
\item \texttt{cos($X$) = $Val$}\index{\texttt{cos/1}}: This function returns the cosine of $X$, where $X$ is given in radians.
\item \texttt{tan($X$) = $Val$}\index{\texttt{tan/1}}: This function returns the tangent of $X$, where $X$ is given in radians.  \ignore{If the tangent is undefined, such as at \texttt{pi / 2}, then this function throws an error.}
\item \texttt{sec($X$) = $Val$}\index{\texttt{sec/1}}: This function returns the secant of $X$, where $X$ is given in radians.  If \texttt{cos($X$)} is $0$, then this function throws an error.
\item \texttt{csc($X$) = $Val$}\index{\texttt{csc/1}}: This function returns the cosecant of $X$, where $X$ is given in radians.  If \texttt{sin($X$)} is $0$, then this function throws an error.
\item \texttt{cot($X$) = $Val$}\index{\texttt{cot/1}}: This function returns the cotangent of $X$, where $X$ is given in radians.  If \texttt{tan($X$)} is $0$, then this function throws an error.
\item \texttt{asin($X$) = $Val$}\index{\texttt{asin/1}}: This function returns the arc sine of $X$, in radians.  The returned value is in the range [\texttt{-pi / 2}, \texttt{pi / 2}].  $X$ must be in the range [$-1$, $1$]; otherwise, this function throws an error.
\item \texttt{acos($X$) = $Val$}\index{\texttt{acos/1}}: This function returns the arc cosine of $X$, in radians.  The returned value is in the range [$0$, \texttt{pi}].  $X$ must be in the range [$-1$, $1$]; otherwise, this function throws an error.
\item \texttt{atan($X$) = $Val$}\index{\texttt{atan/1}}: This function returns the arc tangent of $X$, in radians.  The returned value is in the range [\texttt{-pi / 2}, \texttt{pi / 2}].
\item \texttt{atan2($X$,$Y$) = $Val$}\index{\texttt{atan2/2}}: This function returns the arc tangent of $Y$ / $X$, in radians.  $X$ and $Y$ are coordinates.  The returned value is in the range [\texttt{-pi}, \texttt{pi}].  
\ignore{Note that, if both $X$ and $Y$ are $0$, then this function throws an error.}
\item \texttt{asec($X$) = $Val$}\index{\texttt{asin/1}}: This function returns the arc secant of $X$, in radians.  The returned value is in the range [$0$, \texttt{pi}].  $X$ must be in the range ($-\infty$, $-1$] or [$1$, $\infty$); otherwise, this function throws an error.
\item \texttt{acsc($X$) = $Val$}\index{\texttt{acsc/1}}: This function returns the arc cosecant of $X$, in radians.  The returned value is in the range [\texttt{-pi / 2}, \texttt{pi / 2}].  $X$ must be in the range ($-\infty$, $-1$] or [$1$, $\infty$); otherwise, this function throws an error.
\item \texttt{acot($X$) = $Val$}\index{\texttt{acot/1}}: This function returns the arc cotangent of $X$, in radians.  The returned value is in the range [\texttt{-pi / 2}, \texttt{pi / 2}].
\end{itemize}

\subsection*{Example}
\begin{verbatim}
Picat> S = sin(pi), C = cos(pi), T = tan(pi)
S = 0.0
C = -1.0
T = 0.0
Picat> S = asin(0), C = acos(0), T = atan(0), T2 = atan2(-10, 10)
S = 0.0
C = 1.5708
T = 0.0
T2 = -0.785398
Picat> S = sec(pi / 4), C = csc(pi / 4), T = cot(pi / 4)
S = 1.41421
C = 1.41421
T = 1.0
Picat> S = asec(2), C = acsc(2), T = acot(0)
S = 1.0472
C = 0.5236
T = 1.5708
\end{verbatim}

\subsection{Hyperbolic Functions}
The \texttt{math} module provides the following hyperbolic functions.
\begin{itemize}
\item \texttt{sinh($X$) = $Val$}\index{\texttt{sinh/1}}: This function returns the hyperbolic sine of $X$.
\item \texttt{cosh($X$) = $Val$}\index{\texttt{cosh/1}}: This function returns the hyperbolic cosine of $X$.
\item \texttt{tanh($X$) = $Val$}\index{\texttt{tanh/1}}: This function returns the hyperbolic tangent of $X$.
\item \texttt{sech($X$) = $Val$}\index{\texttt{sech/1}}: This function returns the hyperbolic secant of $X$. 
\item \texttt{csch($X$) = $Val$}\index{\texttt{csch/1}}: This function returns the hyperbolic cosecant of $X$.  If $X$ is $0$, then this function throws an error.
\item \texttt{coth($X$) = $Val$}\index{\texttt{coth/1}}: This function returns the hyperbolic cotangent of $X$.  If $X$ is $0$, then this function throws an error.
\item \texttt{asinh($X$) = $Val$}\index{\texttt{asinh/1}}: This function returns the arc hyperbolic sine of $X$.
\item \texttt{acosh($X$) = $Val$}\index{\texttt{acosh/1}}: This function returns the arc hyperbolic cosine of $X$.  If $X < 1$, then this function throws an error.
\item \texttt{atanh($X$) = $Val$}\index{\texttt{atanh/1}}: This function returns the arc hyperbolic tangent of $X$.  $X$ must be in the range ($-1$, $1$); otherwise, this function throws an error.
\item \texttt{asech($X$) = $Val$}\index{\texttt{asech/1}}: This function returns the arc hyperbolic secant of $X$.  $X$ must be in the range ($0$, $1$]; otherwise, this function throws an error.
\item \texttt{acsch($X$) = $Val$}\index{\texttt{acsch/1}}: This function returns the arc hyperbolic cosecant of $X$.  If $X$ is $0$, then this function throws an error.
\item \texttt{acoth($X$) = $Val$}\index{\texttt{acoth/1}}: This function returns the arc hyperbolic cotangent of $X$.  $X$ must be in the range ($-\infty$, $-1$) or ($1$, $\infty$); otherwise, this function throws an error.
\end{itemize}

\subsection*{Example}
\begin{verbatim}
Picat> S = sinh(pi), C = cosh(pi), T = tanh(pi)
S = 11.54874
C = 11.59195
T = 0.99627
Picat> S = sech(pi / 4), C = csch(pi / 4), T = coth(pi / 4)
S = 0.75494
C = 1.15118
T = 1.52487
Picat> S = asinh(0), C = acosh(1),  T = atanh(0)
S = 0.0
C = 0.0
T = 0.0
\end{verbatim}

\subsection{Random Numbers}
The following functions provide access to a random number generator.
\begin{itemize}
\item \texttt{random() = $Val$}\index{\texttt{random/0}}: This function returns a random integer.
\item \texttt{random2() = $Val$}\index{\texttt{random2/0}}: This function returns a random integer, using an environment-dependent seed.
\item \texttt{rand\_max() = $Val$}\index{\texttt{rand\_max/0}}: This function returns the maximum random integer.
\item \texttt{random($Seed$) = $Val$}\index{\texttt{random/1}}: This function returns a random integer.  At the same time, it changes the seed of the random number generator.
\item \texttt{random($Low$,$High$) = $Val$}\index{\texttt{random/2}}: This function returns a random integer in the range $Low$..$High$.
\item \texttt{frand() = $Val$}\index{\texttt{frand/0}}: This function returns a random real number between 0.0 and 1.0, inclusive.
\item \texttt{frand($Low$,$High$) = $Val$}\index{\texttt{frand/2}}: This function returns a random real number between $Low$ and $High$, inclusive.

%\item \texttt{randrange($From$,$To$) = $Val$}\index{\texttt{randrange/2}}: This function returns a random integer in the range [$From$, $To$).
%\item \texttt{randrange($From$,$Step$,$To$) = $Val$}\index{\texttt{randrange/3}}: This function returns a random integer in the range [$From$, $To$).  The integer will be equal to $From + K * Step$, for some integer $K$.
\end{itemize}

\subsection{Other Built-ins}
\begin{itemize}
\item \texttt{even($N$)}\index{\texttt{even/1}}: This predicate is true if $N$ is an even integer.
\item \texttt{gcd($A$,$B$)}\index{\texttt{gcd/2}}: This function returns the greatest common divisor of integer $A$ and integer $B$.
\item \texttt{odd($N$)}\index{\texttt{odd/1}}: This predicate is true if $N$ is an odd integer.
\item \texttt{prime($N$)}\index{\texttt{prime/1}}: This predicate is true if $N$ is a prime number.
\item \texttt{primes($N$) = $List$}\index{\texttt{primes/1}}: This function returns a list of prime numbers that are less than or equal to $N$.
\end{itemize}


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

\makeindex
\begin{document}
}

\chapter{The \texttt{sys} Module}\label{chapter:sys}
The \texttt{sys} module, which is imported by default, contains built-ins that are relevant to the Picat system.  The built-ins in the \texttt{sys} module perform operations that include compiling programs, tracing execution, and displaying statistics and information about the Picat system.   

\section{Compiling and Loading Programs}
The \texttt{sys} module includes a number of built-ins for compiling programs and loading them into memory.
\begin{itemize}
\item \texttt{compile($FileName$)}\index{\texttt{compile/1}}: This predicate compiles the file \texttt{$FileName$.pi} and all of its dependent files without loading the generated byte-code files.  The destination directory for the byte-code file is the same as the source file's directory.  If the Picat interpreter does not have permission to write into the directory in which a source file resides, then this built-in throws an exception. If \texttt{$FileName$.pi} imports modules, then these module files are also compiled. The system searches for these module files in the directory in which \texttt{$FileName$.pi} resides or the directories that are stored in the environment variable \texttt{PICATPATH}.

\item \texttt{compile\_bp($FileName$)}\index{\texttt{compile\_bp/1}}: This predicate translates the Picat file \texttt{$FileName$.pi} into a B-Prolog file \texttt{$FileName$.pl}.  If the file is dependent on other Picat files, then those files are compiled using \texttt{compile/1}\index{\texttt{compile/1}}.  The destination directory for the B-Prolog file is the same as the source file's directory.  If the Picat interpreter does not have permission to write into the directory in which a source file resides, then this built-in throws an exception.

\item \texttt{load($FileName$)}\index{\texttt{load/1}}: This predicate loads the byte-code file \texttt{$FileName$.qi} and all of its dependent byte-code files into the system for execution.  For $FileName$, the system searches for a byte-code file in the directory specified by $FileName$ or the directories that are stored in the environment variable \texttt{PICATPATH}. For the dependent file names, the system searches for a byte-code file in the directory in which \texttt{$FileName$.qi} resides or the directories that are stored in the environment variable \texttt{PICATPATH}. If the byte-code file \texttt{$FileName$.qi} does not exist, but the source file \texttt{$FileName$.pi} exists, then this built-in compiles the source file and loads the byte codes without creating a \texttt{qi} file.  Note that, for the dependent files, if the byte-code file does not exist, but the source file exists, then the source file will be compiled.

\item \texttt{cl($FileName$)}\index{\texttt{cl/1}}: This predicate compiles and loads the source file named \texttt{$FileName$.pi}.  Note that the extension \texttt{.pi} does not need to be given.  The system also compiles and loads all of the module files that are either directly imported or indirectly imported by the source file.  The system searches for such dependent files in the directory in which \texttt{$FileName$.pi} resides or the directories that are stored in the environment variable \texttt{PICATPATH}.  

\item \texttt{cl}\index{\texttt{cl/0}}: This predicate compiles and loads a program from the console, ending when the end-of-file character ({\tt ctrl-z} for Windows and {\tt ctrl-d} for Unix) is typed.

%For \texttt{$Filename$.pi} and each dependent module file, the compiler creates a byte-code file with the same main name and the extension name \texttt{.qi}.

\item \texttt{cl\_facts($Facts$)}\index{\texttt{cl\_facts/1}}: This predicate compiles and loads facts into the system.  The argument $Facts$ is a list of ground facts.

\item \texttt{cl\_facts($Facts$,$IndexInfo$)}\index{\texttt{cl\_facts/2}}: This predicate compiles and loads facts into the system.  The argument $Facts$ is a list of ground facts.  The argument $IndexInfo$ is a list of indexing information in the form \texttt{p($M_1$,$M_2$,\ldots,$M_n$)}.  Each $M_i$ can either be \texttt{+}, which indicates that the argument is input, or \texttt{-}, which indicates that the argument is output.

\item \texttt{cl\_facts\_table($Facts$)}\index{\texttt{cl\_facts\_table/1}}: This predicate is the same as \texttt{cl\_facts/1}, except that the facts are all tabled.

\item \texttt{cl\_facts\_table($Facts$,$IndexInfo$)}\index{\texttt{cl\_facts\_table/2}}: This predicate is the same as \texttt{cl\_facts/2}, except that the facts are all tabled.
\end{itemize}

\section{Tracing Execution}
The Picat system has three execution modes: \textit{non-trace mode}\index{non-trace mode}, \textit{trace mode}\index{trace mode}, and \textit{spy mode}\index{spy mode}.  In trace mode\index{trace mode}, it is possible to trace the execution of a program, showing every call in every possible stage.  In order to trace the execution, the program must be recompiled while the system is in trace mode\index{trace mode}.  In spy mode\index{spy mode}, it is possible to trace the execution of individual functions and predicates.  The following predicates are used to switch between non-trace mode\index{non-trace mode} and trace mode\index{trace mode}.
\begin{itemize}
\item \texttt{trace}\index{\texttt{trace/0}}: This predicate switches the execution mode to trace mode\index{trace mode}.
\item \texttt{notrace}\index{\texttt{notrace/0}}: This predicate switches the execution mode to non-trace mode\index{non-trace mode}.
\item \texttt{debug}\index{\texttt{debug/0}}: This predicate switches the execution mode to trace mode\index{trace mode}.
\item \texttt{nodebug}\index{\texttt{nodebug/0}}: This predicate switches the execution mode to non-trace mode\index{non-trace mode}.
\item \texttt{spy($Point$)}\index{\texttt{spy/1}}: This predicate places a spy point on $Point$, which is a function or a predicate, optionally followed by an arity.  The creation of a spy point switches the Picat system to spy mode\index{spy mode}.
\item \texttt{nospy}\index{\texttt{nospy/0}}: This predicate removes all spy points, and switches the execution mode to non-trace mode\index{non-trace mode}.
\item \texttt{abort}\index{\texttt{abort/0}}: This predicate terminates the current program.  This can be used in all three execution modes.
\end{itemize}

\subsection{Debugging Commands}
In trace mode\index{trace mode}, the system displays a message when a function or a predicate is entered (\texttt{Call}), exited (\texttt{Exit}), re-entered (\texttt{Redo}) or has failed (\texttt{Fail}).  After a function or a predicate is entered or re-entered, the system waits for a command from the user. A command is a single letter followed by a carriage-return, or may simply be a carriage-return. The following commands are available:  
\begin{itemize}
\item \texttt{+} : create a spy point.
\item \texttt{-} : remove a spy point.
\item \texttt{$<$} : reset the print depth to 10.
\item \texttt{$<$ i} : reset the print depth to \texttt{i}.
\item \texttt{a} : abort, quit debugging, moving control to the top level.
\item \texttt{<cr>} : A carriage return causes the system to show the next call trace. 
\item \texttt{c} :  creep, show the next call trace.
\item \texttt{h} : help, display the debugging commands.
\item \texttt{?} : help, display the debugging commands.
\item \texttt{l} :  leap, be silent until a spy point is encountered. 
\item \texttt{n} : nodebug, prevent the system from displaying debugging messages for the remainder of the program.
\item \texttt{r} : repeat, continue to creep or leap without intervention. 
\item \texttt{s} : skip, be silent until the call is completed (\texttt{Exit} or \texttt{Fail}). 
\item \texttt{t} : backtrace, show the backtrace leading to the current call.
\item \texttt{t i} : backtrace, show the backtrace from the call numbered \texttt{i} to the current call.
\item \texttt{u} : undo what has been done to the current call and redo it.
\item \texttt{u i} : undo what has been done to the call numbered \texttt{i} and redo it.
\end{itemize}

\section{Information about the Picat System}
The \texttt{sys} module contains a number of built-ins that display information about the Picat system.  This information includes statistics about the system, including the memory that is used, and the amount of time that it takes to perform a goal.

\subsection{Statistics}
The following built-ins display statistics about the memory that Picat system uses.
\begin{itemize}
\item \texttt{statistics}\index{\texttt{statistics/0}}: This predicate displays the number of bytes that are allocated to each data area, and the number of bytes that are already in use.
\item \texttt{statistics($Key$,$Value$)}\index{\texttt{statistics/2}}: The statistics concerning $Key$ are $Value$.  This predicate gives multiple solutions upon backtracking.  Keys include \texttt{runtime}, \texttt{program}, \texttt{heap}, \texttt{control}, \texttt{trail}, \texttt{table}, \texttt{gc}, \texttt{backtracks}, and \texttt{gc\_time}.  The values for most of the keys are lists of two elements.  For the key \texttt{runtime}, the first element denotes the amount of time in milliseconds that has elapsed since Picat started, and the second element denotes the amount of time that has elapsed since the previous call to \texttt{statistics/2}\index{\texttt{statistics/2}} was executed.  For the key \texttt{gc}, the number indicates the number of times that the garbage collector\index{garbage collector} has been invoked.  For the key \texttt{backtracks}, the number indicates the number of backtracks that have been done during the labeling of finite domain variables since Picat was started.  For all other keys, the first element denotes the size of memory in use, and the second element denotes the size of memory that is still available in the corresponding data area.
\item \texttt{statistics\_all() = $List$}\index{\texttt{statistics\_all/0}}: This function returns a list of lists that are in the form \texttt{[Key, Value]}.  The list contains all of the keys that \texttt{statistics/2}\index{\texttt{statistics/2}} can display, together with their corresponding values.
\end{itemize} 

\subsection*{Example}
\begin{verbatim}
Picat> statistics
      Stack+Heap:    8,000,000 bytes
        Stack in use:    1,156 bytes
        Heap in use:    28,592 bytes
      
      Program:       8,000,000 bytes
        In use:      1,448,436 bytes
        Symbols:         5,300
      
      Trail:         4,000,000 bytes
        In use:            936 bytes
      
      Memory manager:
         GC:         Call(0), Time(0 ms)
         Expansions: Stack+Heap(0), Program(0), Trail(0), Table(0)

Picat> statistics(Key, Value)
      Key = runtime
      Value = [359947,66060]?;

      Key = program
      Value = [1451656,6548344]?;

      Key = heap
      Value = [34112,7964524]?;

      Key = control
      Value = [1360,7964524]?;

      Key = trail
      Value = [1496,3998504]?;

      Key = table
      Value = [0,4000000]?;

      Key = table_blocks
      Value = 1?;

      key = gc
      Value = 0?;

      Key = backtracks
      V = 0 ?;

      Key = gc_time
      Value = 0 

Picat> L = statistics_all()
L = [[runtime, [359947,66060]], [program, [1451656,6548344]], 
     [heap, [34112,7964524]], [control, [1360,7964524]], 
     [trail, [1496,3998504]], [table, [0,4000000]], 
     [table_blocks,1],[gc, 0], [backtracks, 0], [gc_time, 0]]
\end{verbatim}

\subsection{Time}
The following predicates display the amount of CPU time that it takes to perform a goal.
\begin{itemize}
\item \texttt{time($Goal$)}\index{\texttt{time/1}}: This predicate calls $Goal$, and reports the number of seconds of CPU time that were consumed by the execution.
\item \texttt{time2($Goal$)}\index{\texttt{time2/1}}: This predicate calls $Goal$, and reports the number of seconds of CPU time that were consumed by the execution, and the number of backtracks that have been performed in labeling finite-domain variables during the execution of $Goal$.
\item \texttt{time\_out($Goal$,$Limit$,$Result$)}\index{\texttt{time\_out/3}}: This predicate is logically equivalent to \texttt{once $Goal$}\index{\texttt{once/1}}, except that is imposes a time limit, in milliseconds, on the evaluation.  If $Goal$ is not finished when $Limit$ expires, then the evaluation will be aborted, and $Result$ will be unified with the atom \texttt{time\_out}.  If $Goal$ succeeds within the time limit, then $Result$ will be unified with the atom \texttt{success}. Note that time-out may be delayed or never occur because of the execution of an external C function.
\end{itemize}

\subsection{Other System Information}
\begin{itemize}
\item \texttt{help}\index{\texttt{help/0}}: This predicate displays the usages of some of the commands that the system accepts.
\item \texttt{loaded\_modules() = $List$}:\index{\texttt{loaded\_modules/0}} This function returns a list of the modules that are currently loaded in the Picat system.  This list includes library modules and user-defined modules.  By default, this function returns \texttt{[basic,sys,io,math]}.
\item \texttt{nolog}\index{\texttt{nolog/0}}: This predicate turns off the logging flag.
\item \texttt{picat\_path() = $Path$}\index{\texttt{picat\_path/0}}: This function returns the directories that are stored in the environment variable \texttt{PICATPATH}.  If the environment variable \texttt{PICATPATH} does not exist, then this function throws an error.
\item \texttt{command($String$) = $Int$}\index{\texttt{command/1}}: This function sends the command $String$ to the OS and returns the status that is returned from the OS.
\end{itemize}

\ignore{
\section{The Table}
The \texttt{sys} module includes built-ins that initialize the table area, and built-ins that return answers to tabled goals.  For more about tabling, see Section \ref{chapter:tabling}.
\begin{itemize}
\item \texttt{initialize\_table}\index{\texttt{initialize\_table/0}}: This predicate initializes the table\index{tabling} area.   
\item \texttt{table\_get\_all($Goal$) = $List$}\index{\texttt{table\_get\_all/1}}:  This function returns a list of answers of the subgoals that are subsumed by $Goal$. For example, \texttt{table\_get\_all(\_)}\index{\texttt{table\_get\_all/1}} fetches all of the answers in the table\index{tabling}, since any subgoal is subsumed by the anonymous variable\index{anonymous variable}.
\item \texttt{table\_get\_one($Goal$)}\index{\texttt{table\_get\_one/1}}: If there is a subgoal in the subgoal table\index{tabling} that is a variant of \texttt{$Goal$}, and that has answers, then \texttt{$Goal$} is unified with the first answer. This predicate fails if there is no variant subgoal in the table\index{tabling}, or if there is no answer available.
\end{itemize}
}

\section{Garbage Collection}
Picat incorporates an incremental garbage collector\index{garbage collector} for the control stack and the heap.  The garbage collector\index{garbage collector} is active by default.  The \texttt{sys} module includes the following predicates for garbage collection\index{garbage collector}.
\begin{itemize}
\item \texttt{garbage\_collect}\index{\texttt{garbage\_collect/0}}: This predicate starts the garbage collector\index{garbage collector}.
\item \texttt{garbage\_collect($Size$)}\index{\texttt{garbage\_collect/1}}: This predicate calls the garbage collector\index{garbage collector}. If there are less than $Size$ words on the control stack and heap after garbage collection, then it invokes the memory manager to expand the stack and heap so that there are $Size$ words on the control stack and heap.
\end{itemize}

\section{Quitting the Picat System}
The following predicates can be used to terminate the Picat interpreter.
\begin{itemize}
\item \texttt{exit}\index{\texttt{exit/0}}
\item \texttt{halt}\index{\texttt{halt/0}}
\end{itemize}

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

\makeindex
\begin{document}

}
\chapter{The \texttt{util} Module}
The \texttt{util} module provides general useful utility functions and predicates. This module is expected to be expanded in the future. This module must be imported before use.

\section{Utilities on Terms}
\begin{itemize}
\item \texttt{replace($Term$,$Old$,$New$) = $NewTerm$}\index{\texttt{replace/3}}: This function returns a copy of $Term$, replacing all of the occurrences of $Old$ in $Term$ by $New$.
\item \texttt{replace\_at($Term$,$Index$,$New$) = $NewTerm$}\index{\texttt{replace\_at/3}}: This function returns a copy of $Term$, replacing the argument at $Index$ by $New$. $Term$ must be a compound term.
\item \texttt{find\_first\_of($Term$,$Pattern$) = $Index$}\index{\texttt{find\_first\_of/2}}: This function returns the first index at which the argument unifies with $Pattern$. If there is no argument that unifies with $Pattern$, then this function returns -1. $Term$ must be either a list or a structure.
\item \texttt{find\_last\_of($Term$,$Pattern$) = $Index$}\index{\texttt{find\_last\_of/2}}: This function returns the last index at which the argument unifies with $Pattern$. If there is no argument that unifies with $Pattern$, then this function returns -1. $Term$ must be either a list or a structure.

\end{itemize}


\section{Utilities on Strings and Lists}
\begin{itemize}
\item \texttt{chunks\_of($List$,$K$) = $ListOfLists$}\index{\texttt{chunks\_of/2}}: This function splits $List$ into chunks, each of which has length $K$, and returns the list of the chunks. The last chunk may have less than $K$ elements if the length of $List$ is not a multiple of $K$.
\item \texttt{drop($List$,$K$) = $List$}\index{\texttt{drop/2}}: This function returns the suffix of $List$ after the first $K$ elements are dropped, or [] if $K$ is greater than the length of $List$.
\item \texttt{find($String$,$SubString$,$From$,$To$)}\index{\texttt{find/4}}: This predicate searches for an occurrence of $SubString$ in $String$, and binds $From$ to the starting index and $To$ to the ending index. On backtracking, this predicate searches for the next occurrence of $SubString$.
\item \texttt{find\_ignore\_case($String$,$SubString$,$From$,$To$)}\index{\texttt{find\_ignore\_case/4}}: This predicate is the same as \texttt{find($String$,$SubString$,$From$,$To$)}, except that it is case insensitive.
\item \texttt{join($Tokens$) = $String$}\index{\texttt{join/1}}: This function is the same as \texttt{join($Tokens$," " )}.
\item \texttt{join($Tokens$,$Separator$) = $String$}\index{\texttt{join/2}}: This function concatenates the tokens $Tokens$ into a string, adding $Separator$, which is a string or an atom, between each two tokens.
\item \texttt{lstrip($List$) = $List$}\index{\texttt{lstrip/1}}: This function is the same as \texttt{lstrip($List$,}\verb+" \t\n\r")+. 
\item \texttt{lstrip($List$,$Elms$) = $List$}\index{\texttt{lstrip/2}}: This function returns a copy of $List$ with leading  elements in $Elms$ removed.
\item \texttt{rstrip($List$) = $List$}\index{\texttt{rstrip/1}}: This function is the same as \texttt{rstrip($List$,}\verb+" \t\n\r")+.
\item \texttt{rstrip($List$,$Elms$) = $List$}\index{\texttt{rstrip/2}}: This function returns a copy of $List$ with trailing elements in $Elms$ removed.
\item \texttt{split($String$) = $Tokens$}\index{\texttt{split/1}}: This function is the same as \texttt{split($String$,}\verb+" \t\n\r")+, which uses white spaces as split characters.
\item \texttt{split($String$,$Separators$) = $Tokens$}\index{\texttt{split/2}}: This function splits $String$ into a list of tokens, using characters in the string $Separators$ as split characters. Recall that a string is a list of characters. A token is a string, so the return value is a list of lists of characters.
\item \texttt{strip($List$) = $List$}\index{\texttt{strip/1}}: This function is the same as \texttt{strip($List$,}\verb+" \t\n\r")+. 
\item \texttt{strip($List$,$Elms$) = $List$}\index{\texttt{strip/2}}: This function returns a copy of $List$ with leading and trailing elements in $Elms$ removed.
\item \texttt{take($List$,$K$) = $List$}\index{\texttt{take/2}}: This function returns the prefix of $List$ of length $K$, or $List$ itself if $K$ is greater than the length of $List$.
\end{itemize}

\section{Utilities on Matrices}
An {\it array matrix} is a two-dimensional array. The first dimension gives the number of the rows and the second dimension gives the number of the columns. A {\it list matrix} represents a matrix as a list of lists.

\begin{itemize}
\item \texttt{matrix\_multi($A$,$B$)}\index{\texttt{matrix\_multi/2}}: This function returns the product of matrices $A$ and $B$. Both $A$ and $B$ must be array matrices.
\item \texttt{transpose($A$) = $B$}\index{\texttt{transpose/1}}: This function returns the transpose of the matrix $A$. $A$ can be an array matrix or a list matrix. If $A$ is an array matrix, then the returned transpose is also an array. If $A$ is a list matrix, then the returned transpose is also a list.
\item \texttt{rows($A$) = $List$}\index{\texttt{rows/1}}: This function returns the rows of the matrix $A$ as a list.
\item \texttt{columns($A$) = $List$}\index{\texttt{rows/1}}: This function returns the columns of the matrix $A$ as a list.
\item \texttt{diagonal1($A$) = $List$}\index{\texttt{diagonal1/1}}: This function returns primary diagonal of the matrix $A$ as a list.
\item \texttt{diagonal2($A$) = $List$}\index{\texttt{diagonal2/1}}: This function returns secondary diagonal of the matrix $A$ as a list.
\item \texttt{array\_matrix\_to\_list\_matrix($A$) = $List$}\index{\texttt{array\_matrix\_to\_list\_matrix/1}}: This function converts the array matrix $A$ to a list matrix.
\item \texttt{array\_matrix\_to\_list($A$) = $List$}\index{\texttt{array\_matrix\_to\_list/1}}: This function converts the array matrix $A$ to a flat list, row by row.
\end{itemize}

\section{Utilities on Lists and Sets}
\begin{itemize}
\item \texttt{permutation($List$,$P$)}\index{\texttt{permutation/2}}: This predicate generates a permutation $P$ of $List$. This predicate is non-deterministic. On backtracking, it generates the next permutation.
\item \texttt{permutations($List$) = $Ps$}\index{\texttt{permutations/1}}: This function returns all the permutations of $List$.
\item \texttt{nextto($E1$,$E2$,$List$)}\index{\texttt{nextto/3}}: This predicate is true if \texttt{$E2$} follows \texttt{$E1$} in \texttt{$List$}. This predicate is non-deterministic.
\end{itemize}

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

\makeindex
\begin{document}

}
\chapter{The \texttt{ordset} Module}
An ordered set is represented as a sorted list that does not contain duplicates. The \texttt{ordset} module provides useful utility functions and predicates on ordered sets. This module must be imported before use.

\begin{itemize}
\item \texttt{delete($OSet$,$Elm$) = $OSet_1$}\index{\texttt{delete/2}}: This function returns of a copy of $OSet$ that does not contain the element $Elm$.
\item \texttt{disjoint($OSet_1$,$OSet_2$)}\index{\texttt{disjoint/2}}: This predicate is true when $OSet_1$ and $OSet_2$ have no element in common. 
\item \texttt{insert($OSet$,$Elm$) = $OSet_1$}\index{\texttt{insert/2}}: This function returns a copy of $OSet$ with the element $Elm$ inserted.
\item \texttt{intersection($OSet_1$,$OSet_2$)=$OSet_3$}\index{\texttt{intersection/2}}: This function returns an ordered set that contains elements which are in both $OSet_1$ and $OSet_2$.
\item \texttt{new\_ordset($List$) = $OSet$}\index{\texttt{new\_ordset/1}}: This function returns an ordered set that contains the elements of $List$.
\item \texttt{ordset($Term$)}\index{\texttt{ordset/1}}: This predicate is true if $Term$ is an ordered set.
\item \texttt{subset($OSet_1$,$OSet_2$)}\index{\texttt{subset/2}}: This predicate is true if $OSet_1$ is a subset of $OSet_2$.
\item \texttt{subtract($OSet_1$,$OSet_2$)=$OSet_3$}\index{\texttt{subtract/2}}: This function returns an ordered set that contains all of the elements of $OSet_1$ which are not in $OSet_2$.
\item \texttt{union($OSet_1$,$OSet_2$)=$OSet_3$} \index{\texttt{union/2}}: This function returns an ordered set that contains all of the elements which are present in either $OSet_1$ or $OSet_2$.
\end{itemize}

\ignore{
\end{document}
}
\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:datetime}The \texttt{datetime} Module}

Picat's \texttt{datetime} module provides built-ins for retrieving the date and time. This module must be imported before use.

\begin{itemize}
\item \texttt{current\_datetime() = $DateTime$}\index{\texttt{current\_datetime/0}}: This function returns the current date and time as a structure in the form 
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{date\_time($Year$,$Month$,$Day$,$Hour$,$Minute$,$Second$)}
\end{tabbing}
where the arguments are all integers, and have the following meanings and ranges.

% \begin{table}[h]
\begin{center}
\begin{tabular}{|l|l|l||}
\hline
\textbf{Argument} & \textbf{Meaning} & \textbf{Range} \\
\hline 
\hline 
$Year$ & years since 1900 & an integer \\
$Month$ & months since January & 0-11 \\
$Day$ & day of the month & 1-31 \\
$Hour$ & hours since midnight & 0-23 \\
$Minute$ & minutes after the hour & 0-59 \\
$Second$ & seconds after the minute & 0-60 \\
\hline
\end{tabular}
\end{center}
%\end{table}

\noindent
In the $Month$ argument, $0$ represents January, and $11$ represents December.  In the $Hour$ argument, $0$ represents $12$ AM, and $23$ represents $11$ PM.  In the $Second$ argument, the value $60$ represents a leap second.

\item \texttt{current\_date() = $Date$}\index{\texttt{current\_date/0}}: This function returns the current date as a structure in the form \texttt{date($Year$,$Month$,$Day$)}, where the arguments have the meanings and ranges that are defined above.

\item \texttt{current\_day() = $WDay$}\index{\texttt{current\_day/0}}: This function returns the number of days since Sunday, in the range 0 to 6. 

\item \texttt{current\_time() = $Time$}\index{\texttt{current\_time/0}}: This function returns the current time as a structure in the form \texttt{time($Hour$,$Minute$,$Second$)}, where the arguments have the meanings and ranges that are defined above.

\end{itemize}
\ignore{
\end{document}
}
\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:format}Formats}

\section{Formatted Printing}
The following table shows the specifiers that can be used in formats for the \texttt{writef}\index{\texttt{writef}}, \texttt{printf}\index{\texttt{printf}}, and \texttt{to\_fstring}\index{\texttt{to\_fstring}}.

\begin{table}[h]
\begin{tabular}{|l|l|}
\hline
\textbf{Specifier} & \textbf{Output} \\
\hline 
\hline 
\texttt{\%\%} & Percent Sign \\
\texttt{\%c} & Character \\
\texttt{\%d} & Signed Decimal Integer \\
\texttt{\%e} & Scientific Notation, with Lowercase \texttt{e} \\
\texttt{\%E} & Scientific Notation, with Uppercase \texttt{E} \\
\texttt{\%f}& Decimal Real Number \\
\texttt{\%g} & Shorter of \texttt{\%e} and \texttt{\%f} \\
\texttt{\%G} & Shorter of \texttt{\%E} and \texttt{\%f} \\
\texttt{\%i} & Signed Decimal Integer \\
\texttt{\%n} & Platform-independent Newline \\
\texttt{\%o} &  Unsigned Octal Integer \\
\texttt{\%s} & String \\
\texttt{\%u} & Unsigned Decimal Integer \\
\texttt{\%w} & Term \\
\texttt{\%x} & Unsigned Lowercase Hexadecimal Integer \\
\texttt{\%X} & Unsigned Uppercase Hexadecimal Integer \\
\hline
\end{tabular}
\end{table}

\ignore{
\pagebreak

\section{Formatted Date and Time}
The following table shows that specifiers that can be used in formats for the \texttt{dt\_to\_fstring}\index{\texttt{dt\_to\_fstring/2}} function in the \texttt{datetime} module.

\begin{table}[h]
\begin{tabular}{|l|l|}
\hline
\textbf{Specifier} & \textbf{Output} \\
\hline 
\hline 
\texttt{\%\%} & Percent Sign \\
\texttt{\%a} & Locale-dependent Weekday Name, Abbreviated \\
\texttt{\%A} & Locale-dependent Weekday Name \\
\texttt{\%b} & Locale-dependent Month Name, Abbreviated \\
\texttt{\%B} & Locale-dependent Month Name \\
\texttt{\%c} & Locale-dependent Date and Time \\
\texttt{\%d} & Two-digit Day of the Month \\
\texttt{\%H} & Two-digit Hour (24-hour Time) \\
\texttt{\%I} & Two-digit Hour (12-hour Time) \\
\texttt{\%j} & Three-digit Day of the Year \\
\texttt{\%m} & Two-digit Month \\
\texttt{\%M} & Two-digit Minute \\
\texttt{\%p} & \texttt{AM} or \texttt{PM} \\
\texttt{\%S} & Two-digit Second \\
\texttt{\%w} & One-digit Day of the Week \\
\texttt{\%x} & Locale-dependent Date \\
\texttt{\%X} & Locale-dependent Time \\
\texttt{\%y} & Two-digit Year \\
\texttt{\%Y} & Four-digit Year \\
\hline
\end{tabular}
\end{table}
}
\ignore{
\end{document}
}
\ignore{
\documentstyle[11pt]{report}
\textwidth 13.7cm
\textheight 21.5cm
\newcommand{\myimp}{\verb+ :- +}
\newcommand{\ignore}[1]{}
\def\definitionname{Definition}

\makeindex
\begin{document}
}
\chapter{\label{ch:cinterface}External Language Interface with C}
Picat has an interface with C, through which Picat programs can call deterministic predicates that are written as functions in C. C programs that use this interface must include the file \texttt{"picat.h"} in the directory \texttt{Picat/Emulator}. In order to make C-defined predicates available to Picat, users have to re-compile Picat's C source code together with the newly-added C functions.


%\section{Calling C from Picat}
\section{Term Representation}
Picat's C interface provides functions for accessing, manipulating, and building Picat terms. In order to understand these functions, users need to know how terms are represented in Picat's virtual machine.

A term is represented by a word that contains a value and a tag. A word has 32 bits or 64 bits, depending on the underlying CPU and OS. The tag in a word distinguishes the type of the term. 

The value of a term is an address, except when the term is an integer (in which case, the value represents the integer itself).  The location to which the address points is dependent on the type of the term.  In a reference, the address points to the referenced term. An unbound variable is represented by a self-referencing pointer. In an atom, the address points to the record for the atom symbol in the symbol table.  In a structure, $f(t_1,\ldots,t_n)$, the address points to a block of $n+1$ consecutive words, where the first word points to the record for the functor, \emph{f/n}, in the symbol table, and the remaining $n$ words store the components of the structure. Arrays, floating-point numbers, and big integers are represented as special structures. Picat lists are singly-linked lists. In a list, \emph{[H$|$T]}, the address points to a block of two consecutive words, where the first word stores the car, \emph{H}, and the second word stores the cdr, \emph{T}. 

\section{Fetching Arguments of Picat Calls} 
A C function that defines a Picat predicate should not take any argument. The following function is used in order to fetch arguments in the current Picat call.
\begin{itemize}
\item \texttt{TERM picat\_get\_call\_arg(int i, int arity)}: Fetch the \texttt{i}th argument, where \texttt{arity} is the arity of the predicate, and \texttt{i} must be an integer between 1 and \texttt{arity}. The validity of the arguments is not checked, and an invalid argument may cause fatal errors.
\end{itemize}

\section{Testing Picat Terms} 
The following functions are provided for testing Picat terms. They return \texttt{PICAT\_TRUE} when they succeed and \texttt{PICAT\_FALSE} when they fail.
\begin{itemize}
\item \texttt{int picat\_is\_var(TERM t)}: Term \texttt{t} is a variable.   
\item \texttt{int picat\_is\_attr\_var(TERM t)}: Term \texttt{t} is an attributed variable.   
\item \texttt{int picat\_is\_dvar(TERM t)}: Term \texttt{t} is an attributed domain variable.   
\item \texttt{int picat\_is\_bool\_dvar(TERM t)}: Term \texttt{t} is an attributed Boolean variable.   
\item \texttt{int picat\_is\_integer(TERM t)}: Term \texttt{t} is an integer.   
\item \texttt{int picat\_is\_float(TERM t)}: Term \texttt{t} is a floating-point number.   
\item \texttt{int picat\_is\_atom(TERM t)}: Term \texttt{t} is an atom.   
\item \texttt{int picat\_is\_nil(TERM t)}: Term \texttt{t} is nil, i.e., the empty list \texttt{[]}.   
\item \texttt{int picat\_is\_list(TERM t)}: Term \texttt{t} is a list.   
\item \texttt{int picat\_is\_string(TERM t)}: Term \texttt{t} is a string.
\item \texttt{int picat\_is\_structure(TERM t)}: Term \texttt{t} is a structure (but not a list).   
\item \texttt{int picat\_is\_array(TERM t)}: Term \texttt{t} is an array.   
\item \texttt{int picat\_is\_compound(TERM t)}: True if either \texttt{picat\_is\_list(t)} \\ or \texttt{picat\_is\_structure(t)} is true.   
\item \texttt{int picat\_is\_identical(TERM t1, TERM t2)}: \texttt{t1} and \texttt{t2} are identical. This function is equivalent to the Picat call \texttt{t1 == t2}.
\item \texttt{int picat\_is\_unifiable(TERM t1, TERM t2)}: \texttt{t1} and \texttt{t2} are unifiable. This is equivalent to the Picat call \texttt{not(not(t1 = t2))}.
\end{itemize}

\section{Converting Picat Terms into C}
The following functions convert Picat terms to C. If a Picat term does not have the expected type, then the global C variable \texttt{exception}, which is of type \texttt{Term}, is assigned a term. A C program that uses these functions must check \texttt{exception} in order to see whether data are converted correctly. The converted data are only correct when \texttt{exception} is \texttt{(TERM)NULL}.

\begin{itemize}
\item \texttt{long picat\_get\_integer(TERM t)}: Convert the Picat integer \texttt{t} into C. The term \texttt{t} must be an integer; otherwise \texttt{exception} is set to \texttt{integer\_expected} and 0 is returned. Note that precision may be lost if \texttt{t} is a big integer.

\item \texttt{double picat\_get\_float(TERM t)}: Convert the Picat float \texttt{t} into C. The term \texttt{t} must be a floating-point number; otherwise \texttt{exception} is set to \texttt{number\_expected}, and 0.0 is returned. 

\item \texttt{(char *) picat\_get\_atom\_name(TERM t)}: Return a pointer to the string that is the name of atom \texttt{t}. The term \texttt{t} must be an atom; otherwise, \texttt{exception} is set to \texttt{atom\_expected}, and \texttt{NULL} is returned. 

\item \texttt{(char *) picat\_get\_struct\_name(TERM t)}: Return a pointer to the string that is the name of structure \texttt{t}. The term \texttt{t} must be a structure; otherwise, \texttt{exception} is set to \texttt{structure\_expected}, and \texttt{NULL} is returned. 

\item \texttt{(char *) picat\_get\_struct\_name(TERM t)}: Return a pointer to the string that is the name of structure \texttt{t}. The term \texttt{t} must be a structure; otherwise, \texttt{exception} is set to \texttt{structure\_expected}, and \texttt{NULL} is returned. 

\item \texttt{int picat\_get\_struct\_arity(TERM t)}: Return the arity of term \texttt{t}.  The term \texttt{t} must be a structure; otherwise, \texttt{exception} is set to \texttt{structure\_expected} and 0 is returned.
\end{itemize}

\section{Manipulating and Writing Picat Terms} 
\begin{itemize}
\item \texttt{int picat\_unify(TERM t1,TERM t2)}: Unify two Picat terms \texttt{t1} and \texttt{t2}. The result is \texttt{PICAT\_TRUE} if the unification succeeds, and \texttt{PICAT\_FALSE} if the unification fails.

\item \texttt{TERM picat\_get\_arg(int i,TERM t)}: Return the \texttt{i}th argument of term \texttt{t}. The term \texttt{t} must be compound, and \texttt{i} must be an integer that is between 1 and the arity of \texttt{t}; otherwise, \texttt{exception} is set to \texttt{compound\_expected}, and the Picat integer \texttt{0} is returned.

\item \texttt{TERM picat\_get\_car(TERM t)}: Return the car of the list \texttt{t}. The term \texttt{t} must be a non-empty list; otherwise \texttt{exception} is set to \texttt{list\_expected}, and the Picat integer \texttt{0} is returned.

\item \texttt{TERM picat\_get\_cdr(TERM t)}: Return the cdr of the list \texttt{t}. The term \texttt{t} must be a non-empty list; otherwise \texttt{exception} is set to \texttt{list\_expected}, and the Picat integer \texttt{0} is returned.

\item \texttt{void picat\_write\_term(TERM t)}: Send term \texttt{t} to the standard output stream.
\end{itemize}

\section{Building Picat Terms}
\begin{itemize}
\item \texttt{TERM picat\_build\_var()}: Return a free Picat variable.

\item \texttt{TERM picat\_build\_integer(long i)}: Return a Picat integer whose value is \texttt{i}.

\item \texttt{TERM picat\_build\_float(double f)}: Return a Picat float whose value is \texttt{f}.

\item \texttt{TERM picat\_build\_atom(char *name)}: Return a Picat atom whose name is \texttt{name}.

\item \texttt{TERM picat\_build\_nil()}: Return an empty Picat list.

\item \texttt{TERM picat\_build\_list()}: Return a Picat list whose car and cdr are free variables.

\item \texttt{TERM picat\_build\_structure(char *name, int arity)}: Return a Picat structure whose functor is \texttt{name}, and whose arity is \texttt{arity}.  The structure's arguments are all free variables.

\item \texttt{TERM picat\_build\_array(int n)}: Return a Picat array whose size is \texttt{n}.  The array's arguments are all free variables.
\end{itemize}

\section{Registering C-defined Predicates}
The following function registers a predicate that is defined by a C function.
\begin{verbatim}
       insert_cpred(char *name, int arity, int (*func)())
\end{verbatim}
The first argument is the predicate name, the second argument is the arity, and the third argument is the name of the function that defines the predicate. The function that defines the predicate cannot take any argument. As described above, \texttt{picat\_get\_call\_arg(i,arity)} is used to fetch arguments from the Picat call.

For example, the following registers a predicate whose name is \texttt{"p"}, and whose arity is 2.
\begin{verbatim}
       extern int p();	
       insert_cpred("p", 2, p)
\end{verbatim}
The C function's name does not need to be the same as the predicate name.

Predicates that are defined in C should be registered after the Picat engine is initialized, and before any call is executed. One good place for registering predicates is the \texttt{Cboot()} function in the file \texttt{cpreds.c}, which registers all of the C-defined built-ins of Picat. After registration, the predicate can be called. All C-defined predicates must be explicitly called with the module qualifier \texttt{bp}, as in \texttt{bp.p(a,X)}.

\section*{Example}
Consider the Picat predicate:
\begin{verbatim}
      p(a,X) => X = $f(a).
      p(b,X) => X = [1].
      p(c,X) => X = 1.2.
\end{verbatim}
where the first argument is given and the second is unknown. The following steps show how to define this predicate in C, and how to make it callable from Picat.

\begin{description}
\item [Step 1]. Write a C function to implement the predicate. The following shows a sample:
\begin{verbatim}
#include "picat.h"

p(){
  TERM a1, a2, a, b, c, f1, l1, f12;
  char *name_ptr;
  
  /*   prepare Picat terms */
  a1 = picat_get_call_arg(1, 2);       /* first argument */
  a2 = picat_get_call_arg(2, 2);       /* second argument */
  a = picat_build_atom("a");
  b = picat_build_atom("b");
  c = picat_build_atom("c");
  f1 = picat_build_structure("f", 1);  /* f(a) */
  picat_unify(picat_get_arg(1, f1), a);
  l1 = picat_build_list();             /* [1] */ 
  picat_unify(picat_get_car(l1), picat_build_integer(1));
  picat_unify(picat_get_cdr(l1), picat_build_nil());
  f12 = picat_build_float(1.2);        /* 1.2 */
  
  /* code for the rules */
  if (!picat_is_atom(a1)) 
      return PICAT_FALSE;
  name_ptr = picat_get_atom_name(a1);
  switch (*name_ptr){
  case 'a': 
    return (picat_unify(a1, a) ? 
               picat_unify(a2, f1) : PICAT_FALSE);
  case 'b': 
    return (picat_unify(a1, b) ? 
               picat_unify(a2, l1) : PICAT_FALSE);
  case 'c': 
    return (picat_unify(a1, c) ? 
               picat_unify(a2, f12) : PICAT_FALSE);
  default: return PICAT_FALSE;
  }
}
\end{verbatim}

\item [Step 2]. Insert the following two lines into \texttt{Cboot()} in \texttt{cpreds.c}:
\begin{verbatim}
      extern int p();
      insert_cpred("p", 2, p);
\end{verbatim}
\item [Step 3]. Modify the make file, if necessary, and recompile the system. Now, \texttt{p/2} is in the group of built-ins in Picat.

\item [Step 4]. Use \texttt{bp.p(...)} to call the predicate.
\begin{verbatim}
      picat> bp.p(a,X)
      X = f(a)
\end{verbatim}

\end{description}

\ignore{
\section{Calling Picat from C} 
In order to make Picat predicates callable from C, one must replace the \texttt{main.c} file in the emulator with a new file that starts his/her own application. The following function must be executed before any call to Picat predicates is executed: 
\begin{verbatim}
       initialize_bprolog(int argc, char *argv[])
\end{verbatim}
\index{\texttt{initialize\_bprolog}}
In addition, the environment variable \texttt{BPDIR} must be correctly set to the home directory where Picat was installed. The function \texttt{initialize\_bprolog()} allocates all of the stacks that are used in Picat, initializes them, and loads the byte code file \texttt{bp.out} into the program area. \texttt{PICAT\_ERROR} is returned if the system cannot be initialized.

A query can be a string or a Picat term, and a query can return one or more solutions.

\begin{itemize}
\item \texttt{int picat\_call\_string(char *goal)}\index{\texttt{picat\_call\_string}}:
 This function executes the Picat call, as represented by the string \texttt{goal}. The return value is \texttt{PICAT\_TRUE} if the call succeeds, \texttt{PICAT\_FALSE} if the call fails, and \texttt{PICAT\_ERROR} if an exception occurs. Examples:
\begin{verbatim}
      picat_call_string("load(myprog)")
      picat_call_string("X is 1+1")
      picat_call_string("p(X,Y), q(Y,Z)")
\end{verbatim}
\item \texttt{picat\_call\_term(TERM goal)}\index{\texttt{picat\_call\_term}}:
 This function is similar to \texttt{picat\_call\_string}, except that it executes the Picat call, as represented by the term \texttt{goal}. While \texttt{picat\_call\_string} cannot return any bindings for variables, this function can return results through the Picat variables in \texttt{goal}.  Example:
\begin{verbatim}
      TERM call = picat_build_structure("p", 2);
      picat_call_term(call);
\end{verbatim}
\item \texttt{picat\_mount\_query\_string(char *goal)}:
 Mount \texttt{goal} as the next Picat goal to be executed.
\item \texttt{picat\_mount\_query\_string(TERM goal)}:
 Mount \texttt{goal} as the next Picat goal to be executed.
\item \texttt{picat\_next\_solution()}:
 Retrieve the next solution of the current goal. If no goal is mounted before this function, then the exception \texttt{illegal\_predicate} will be raised, and \texttt{PICAT\_ERROR} will be returned as the result. If no further solution is available, then the function returns \texttt{PICAT\_FALSE}. Otherwise, the next solution is found.
\end{itemize}

\subsubsection*{Example}
\begin{picture}(380,1)(0,0)
\put (0,0){\framebox(380,1)}
\end{picture}

\noindent
This example program retrieves all of the solutions of the query \texttt{member(X,[1,2,3])}\index{\texttt{member/2}}. 
\begin{verbatim}
#include "bprolog.h"

main(int argc, char *argv[])
{
  TERM query;
  TERM list0, list;
  int res;
  
  initialize_bprolog(argc, argv);
  /* build the list [1,2,3] */
  list = list0 = picat_build_list();
  picat_unify(picat_get_car(list), picat_build_integer(1));
  picat_unify(picat_get_cdr(list), picat_build_list());
  list = picat_get_cdr(list);
  picat_unify(picat_get_car(list), picat_build_integer(2));
  picat_unify(picat_get_cdr(list), picat_build_list());
  list = picat_get_cdr(list);
  picat_unify(picat_get_car(list), picat_build_integer(3));
  picat_unify(picat_get_cdr(list), picat_build_nil());

  /* build the call member(X,list) */
  query = picat_build_structure("member", 2);
  picat_unify(picat_get_arg(2, query), list0);

  /* invoke member/2 */
  picat_mount_query_term(query);
  res = picat_next_solution();
  while (res == PICAT_TRUE) {
    picat_write(query); 
    printf("\n");
    res = picat_next_solution();
  }
}
\end{verbatim}
In order to run the program, users need to replace the content of the file \texttt{main.c} in \texttt{\$BPDIR/Emulator} with this program, and then recompile the system. The newly compiled system will give the following output when it is started.
\begin{verbatim}
      member(1,[1,2,3])
      member(2,[1,2,3])
      member(3,[1,2,3])
\end{verbatim}
\begin{picture}(380,1)(0,0)
\put (0,0){\framebox(380,1)}
\end{picture}
}
\ignore{
\end{document}
}
\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:lex}Appendix: Tokens}
\begin{scriptsize}
\begin{verbatim}
/* Picat lexical rules 
      [...] means optional
      {...} means 0, 1, or more occurrences
      "..." means as-is
      /*  ... */ comment

   Tokens to be returned:

      Token-type     lexeme
     =====================
      ATOM           a string of chars of the atom name
      VARIABLE       a string of chars of the variable name
      INTEGER        an integer literal
      FLOAT          a float literal
      STRING         a string of chars 
      OPERATOR       a string of chars in the operator
      SEPARATOR      one of "(" ")" "{" "}"  "[" "]"  
*/
line_terminator ->
    the LF character, also known as "newline"
    the CR character, also known as "return"
    the CR character followed by the LF character

input_char ->
    utf8_char but not CR or LF

comment ->
    traditional_comment
    end_of_line_comment

traditional_comment ->
    "/*" comment_tail

comment_tail ->
    "*" comment_tail_star
    not_star comment_tail

comment_tail_star ->
    "/"
    "*" comment_tail_star
    not_star_not_slash comment_tail

not_star ->
    input_char but not "*"
    line_terminator

not_star_not_slash ->
    input_char but not "*" or "/"
    line_terminator

end_of_line_comment ->
    "%" {input_char} line_terminator

white_space ->
    the SP character, also known as "space"
    the HT character, also known as "horizontal tab"
    the FF character, also known as "form feed"
    line_terminator

token ->
    atom_token
    variable_token
    integer_literal
    real_literal
    string_literal
    operator_token
    separator_token

atom_token ->
    small_letter {alphanumeric_char}
    single_quoted_token
   
variable_token ->
    anonymous_variable
    named_variable 

anonymous variable ->
    "_"

named_variable ->
    "_" alphanumeric {alphanumeric}
    capital_letter {alphanumeric} 

alphanumeric ->
    alpha_char
    decimal_digit
    
alpha_char ->
    underscore_char
    letter

letter ->
    small_letter
    capital_letter

single_quoted_token ->
    "'" {string_char} "'"

string_literal ->
    "\"" {string_char} "\""

string_char ->
    input_char 
    escape_sequence
    
integer_literal ->
    decimal_numeral 
    hex_numeral 
    octal_numeral 
    binary_numeral

decimal_numeral ->
    decimal_digit [decimal_digits_and_underscores]

decimal_digits_and_underscores ->
    decimal_digit_or_underscore
    decimal_digits_and_underscores decimal_digit_or_underscore 

decimal_digit_or_underscore ->
    decimal_digit
    "_"

hex_numeral ->
    "0x" hex_digits
    "0X" hex_digits

hex_digits ->
    hex_digit [hex_digits_and_underscores]

hex_digits_and_underscores ->
    hex_digit_or_underscore
    hex_digits_and_underscores hex_digit_or_underscore

hex_digit_or_underscore ->
    hex_digit
    "_"

octal_numeral ->
    "0O" octal_digits
    "0o" octal_digits

octal_digits ->
    octal_digit [octal_digits_and_underscores] 

octal_digits_and_underscores ->
    octal_digit_or_underscore
    octal_digits_and_underscores octal_digit_or_underscore

octal_digit_or_underscore ->
    octal_digit
    "_"

binary_numeral ->
    "0b" binary_digits 
    "0B" binary_digits

binary_digits:
    binary_digit [binary_digits_and_underscores]

binary_digits_and_underscores ->
    binary_digit_or_underscore 
    binary_digits_and_underscores binary_digit_or_underscore 

binary_digit_or_underscore:
    binary_digit
    "_" 

real_literal ->
    decimal_numeral "." decimal_numeral [exponent_part] 

exponent_part ->
    exponent_indicator signed_integer

exponent_indicator ->
    "e" 
    "E"

signed_integer ->
    [sign] decimal_numeral

sign ->
    "+"
    "-"

separator ->
    one of "(" ")" "{" "}"  "[" "]"  

operator ->
    one of
      "=" "!=" ">" ">=" "<" "<=" "=<" ".." "!"
      "," ";" ":" "::" "." ". " (dot-whitespace)
      "=>" "?=>" "==" "!==" ":=" "|" "$" "@"
      "/\" "\/" "~" "^" "<<" ">>"
      "+" "-" "*" "**" "/" "/>" "/<" "^" 
      "#=" "#!=" "#>" "#>=" "#<" "#<=" "#=<"
      "#/\" "#\/" "#~" "#^" "#=>" "#<=>"
      "@>" "@>=" "@<" "@<=" "@=<"

small_letter ->
    one of "a" "b" ... "z"

capital_letter ->
    one of "A" "B" ... "Z"

decimal_digit ->
    one of "0" "1" "2" "3" "4" "5" "6" "7" "8" "9"

hd ->
    hex_digit

hex_digit ->
    one of 
       "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" 
       "a" "b" "c" "d" "e" "f" "A" "B" "C" "D" "E" "F"

octal_digit ->
    one of "0" "1" "2" "3" "4" "5" "6" "7"

binary_digit ->
    one of "0" "1" 

escape_sequence ->
    "\""             /* double quote " */
    "\'"             /* single quote ' */
    "\\"             /* backslash \ */
    "\`"             /* back quote ` */
    "\a"             /* alarm */
    "\b"             /* backspace */
    "\f"             /* form feed */
    "\n"             /* line feed */
    "\r"             /* carriage return */
    "\t"             /* horizontal tab */
    "\uhh...h"       /* unicode (utf-8) code point */
    "\v"             /* vertical tab */
\end{verbatim}
\end{scriptsize}
\ignore{
\end{document}
}
\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:syntax}Appendix: Grammar}
\begin{scriptsize}
\begin{verbatim}
/* Picat syntax rules 
      [...] means optional
      {...} means 0, 1, or more occurrences
      (a | b) means choice
      "..." means a token
      %... one-line comment
      input tokens:
            atom
            variable
            integer
            float
            operator
            separator
            eor is "." followed by a white space or eof
*/
program ->
    [module_declaration]
    {import_declaration}
    program_body

program_body ->
    {predicate_definition | function_definition | actor_definition}

module_declaration -> 
    "module" atom eor

import_declaration ->
    import import_item {"," import_item} eor

import_item ->
    atom 

predicate_definition ->
    {predicate_directive} predicate_rule_or_fact {predicate_rule_or_fact}

function_definition ->
    {function_directive} function_rule_or_fact {function_rule_or_fact}

actor_definition ->
    ["private"] action_rule {(action_rule 
                              | nonbacktrackable_predicate_rule)}

function_directive ->
    "private"
    "table"

predicate_directive ->
    "private"
    "table" ["(" table_mode {"," table_mode} ")" ]
    "index" index_declaration {"," index_declaration}

index_declaration ->
    "(" index_mode {"," index_mode} ")"

index_mode ->
   "+"
   "-"
   
table_mode ->
   "+"
   "-"
   "min"
   "max"
   "nt"
      
predicate_rule_or_fact ->
    predicate_rule
    predicate_fact

function_rule_or_fact ->
    function_rule
    function_fact

predicate_rule ->
    head ["," condition] ("=>" | "?=>") body eor
    head (":-" | "-->") body eor

nonbacktrackable_predicate_rule ->
    head ["," condition] "=>" body eor

predicate_fact ->
    head eor

head ->
    atom ["(" [term {"," term}] ")"]

function_rule ->
    head "=" expression ["," condition] "=>" body eor    

function_fact ->
    head "=" argument eor

action_rule ->
    head ["," condition] "," "{" event_pattern "}"   => body eor

event_pattern ->
    term {',' term}

condition -> goal

body -> goal

argument ->
    negative_goal

goal ->
    disjunctive_goal

disjunctive_goal ->
    disjunctive_goal ";" conjunctive_goal
    conjunctive_goal

conjunctive_goal ->
    conjunctive_goal ","  negative_goal
    negative_goal

negative_goal ->
   "not" negative_goal
   equiv_constr

equiv_constr ->
   equiv_constr "#<=>" impl_constr
   impl_constr

impl_constr ->
   impl_constr "#=>" or_constr
   or_constr

or_constr ->
   or_constr "#\/" xor_constr
   xor_constr

xor_constr ->
   xor_constr "#^" and_constr
   and_constr

and_constr ->
   and_constr "#/\" not_constr
   not_constr

not_constr ->
   "#~" not_constr
   enclosed_goal

enclosed_goal ->
   "if" if_cond goal {"elseif" if_cond goal} "else" goal "end"
   "foreach" "(" iterator {"," (iterator | condition)} ")" goal "end"
   "while" "(" goal ")" ["do"] goal "end"
   "do" goal "while" "(" goal ")"
   expression {bin_rel_op expression}

if_cond -> "(" goal ")" ["then"]       % "then" is optional
if_cond -> goal "then"                 % "then" is mandated if goal is not enclosed in parentheses

bin_rel_op ->
    "=" 
    "!="
    ":=" 
    "=="
    "!=="
    ">"
    ">="
    "<"
    "=<"
    "<="
    "::"
    "in"
    "notin"
    "#=" 
    "#!=" 
    "#>" 
    "#>=" 
    "#<" 
    "#=<" 
    "#<=" 
    "@>" 
    "@>=" 
    "@<" 
    "@=<" 
    "@<=" 

expression -> 
    concat_expression 

concat_expression ->
    range_expression ["++" concat_expression]

range_expression ->
   or_expression [".." or_expression [".." or_expression]]
    
or_expression  ->
    xor_expression 
    or_expression "\/" xor_expression

xor_expression ->  
    and_expression 
    xor_expression "^" and_expression              % bit-wise xor

and_expression ->
    shift_expression 
    and_expression  "/\" shift_expression

shift_expression ->
    additive_expression 
    shift_expr ( "<<" | ">>" ) additive_expression 

additive_expression ->
    multiplicative_expression
    additive_expression "+" multiplicative_expression
    additive_expression "-" multiplicative_expression

multiplicative_expression ->
    unary_expression
    multiplicative_expression "*" unary_expression
    multiplicative_expression "/" unary_expression
    multiplicative_expression "//" unary_expression
    multiplicative_expression "/>" unary_expression
    multiplicative_expression "/<" unary_expression
    multiplicative_expression "div" unary_expression
    multiplicative_expression "mod" unary_expression
    multiplicative_expression "rem" unary_expression

    
unary_expression ->
    power_expression
    "+" unary_expression
    "-" unary_expression
    "~" unary_expression                           % bit-wise complement

power_expression ->
    primary_expression ["**" unary_expression]

primary_expression ->
    "(" goal ")"
    variable "[" argument ["," argument] "]"       % subscript notation
    variable "@" term ["@"]                        % as-pattern
    variable
    integer
    float
    atom_or_call
    list_expression
    array_expression
    function_call
    term_constructor
    primary_expression "." atom_or_call            % dot-notation

atom_or_call ->
    atom ["(" [argument {"," argument}] ")"]  

list_expression ->
    "[]"
    "[" argument list_expression_suffix "]"

list_expression_suffix ->
    ":" iterator {"," (iterator | condition)}      % list comprehension
    {"," argument} ["|" argument] 

array_expression ->
    "{}"
    "{" argument array_expression_suffix "}"    

array_expression_suffix ->
    ":" iterator {"," (iterator | condition)}      % array comprehension
    {"," argument} 

function_call ->
    [primary_expression "."] atom "(" [argument {"," argument}] ")"

variable_list ->
    "[" [variable {"," variable}] "]"

term_constructor ->
    "$" goal ["$"]

/* a term has the same form as a goal except that it cannot contain loops 
   or if statements. Note that subscript notations, range expressions, dot
   notations, and list comprehensions are still treated as functions in 
   term constructors */

\end{verbatim}
\end{scriptsize}
\ignore{
\end{document}
}
\chapter{Appendix: Operators}

\vspace*{2cm}

\begin{center}
\begin{tabular}{ |c|c| } \hline
Precedence & Operators  \\ \hline \hline
Highest    & \verb+.+, \verb+@+ \\ \hline
           & \verb+**+ (right-associative) \\ \hline
           & unary \verb-+-, unary \verb+-+, \verb+~+  \\ \hline 
           & \verb+*+, \verb+/+, \verb+//+, \verb+/<+, \verb+/>+, \verb+div+, \verb+mod+, \verb+rem+ \\ \hline 
           & binary \verb-+-, binary \verb+-+ \\ \hline 
           & \verb+>>+, \verb+<<+ \\ \hline 
           & \verb+/\+ \\ \hline 
           & \verb+^+ \\ \hline 
           & \verb+\/+ \\ \hline 
           & \verb+..+ \\ \hline 
           & \verb-++- (right-associative) \\ \hline 
           & \verb+=+, \verb+!=+,  \verb+:=+,  \verb+==+, \verb+!==+, \verb+=:=+, \verb+<+,  \verb+=<+, \verb+<=+, \verb+>+,  \verb+>=+, \verb+::+, \verb+in+, \verb+notin+, \verb+=..+  \\ 
           &  \verb+#=+,  \verb+#!=+, \verb+#<+,  \verb+#=<+, \verb+#<=+, \verb+#>+, \verb+#>=+, \verb+@<+, \verb+@=<+, \verb+@<=+, \verb+@>+, \verb+@>=+  \\ \hline 
           & \verb+#~+ \\ \hline 
           & \verb+#/\+ \\ \hline 
           & \verb+#^+ \\ \hline 
           & \verb+#\/+ \\ \hline 
           & \verb+#=>+ (right-associative)\\ \hline 
           & \verb+#<=>+ \\ \hline 
           & \verb+not+, \verb+once+, \verb-\+-  \\ \hline 
           & \verb+,+ (right-associative), $\&\&$ (right-associative) \\ \hline 
Lowest     & \verb+;+ (right-associative), $|$$|$ (right-associative) \\ \hline
\end{tabular}
\end{center}



\begin{adjustwidth}{-2cm}{-1cm}
\ignore{
\documentclass[10pt]{article}
\usepackage{fancyhdr}
\usepackage{graphicx}
\usepackage{wrapfig}
\usepackage{multicol}
\usepackage{setspace}
\usepackage{makeidx}
\newcommand{\ignore}[1]{}
\usepackage{vmargin}
\setpapersize{USletter}
\setmarginsrb{19mm}{19mm}{19mm}{19mm}{12pt}{5mm}{0pt}{0mm}
\usepackage{url}
\usepackage{times}
\usepackage{sectsty}
\sectionfont{\normalsize\bf}
\subsectionfont{\normalsize\bf}
\graphicspath{{figs/}}
\parindent 20pt
%\parskip 4pt
\newcommand{\mainfont}{ }
\newcommand{\headfont}{\itshape}
%
%\newcommand{\mainfont}{\sffamily}
%\pagestyle{fancy}
\lhead{{\bfseries\headfont Picat}}
%\rhead{{\bfseries\headfont Page~{\protect\thepage~of~\pageref{LastPage}}}}
\rhead{{\bfseries\headfont Page~{\protect\thepage}}}
%\chead{Google Faculty Research Awards Program}
\cfoot{}
\begin{document}
\begin{center}
\noindent {\bf The Library Modules of Picat} \\ 
\vspace*{5mm}
Neng-Fa Zhou and Jonathan Fruhman \\
\vspace*{5mm}
January 14, 2013 \\
\vspace*{5mm}
\end{center}
}
\chapter{Appendix: The Library Modules}
\setstretch{0.5}
\begin{multicols}{2}
\section*{ Module \texttt{basic} (imported by default)}
\begin{scriptsize}
\begin{itemize}
    \item {\tt \verb-\+- $Call$} 
    \item {\tt $X$ \verb+!=+ $Y$} 
    \item {\tt $X$ \verb+!==+ $Y$}
    \item {\tt $X$ \verb+:=+ $Y$} 
    \item {\tt $X$ \verb+<+ $Y$} 
    \item {\tt $X$ \verb+<=+ $Y$} 
    \item {\tt $X$ \verb+=+ $Y$} 
    \item {\tt $X$ \verb+=<+ $Y$} 
    \item {\tt $X$ \verb+=:=+ $Y$}
    \item {\tt $X$ \verb+=\=+ $Y$}    
    \item {\tt $X$ \verb+==+ $Y$} 
    \item {\tt $X$ \verb+>+ $Y$} 
    \item {\tt $X$ \verb+>=+ $Y$} 
    \item {\tt $X$ @< $Y$} 
    \item {\tt $X$ @<= $Y$} 
    \item {\tt $X$ @=< $Y$} 
    \item {\tt $X$ @> $Y$} 
    \item {\tt $X$ @>= $Y$}
    \item {\tt $X$\ =..\ $Y$} 
    \item {\tt $Term_1$ \verb-++- $Term_2$ = $List$} 
    \item {\tt \verb+[+$X$ : $I$ in $D$,$\ldots$ \verb+]+ = $List$}
    \item {\tt $L$ \verb+..+ $U$ = $List$} 
    \item {\tt $L$ \verb+..+ $Step$ \verb+..+ $U$ = $List$} 
    \item {\tt \verb+-+$X$ = $Y$}
    \item {\tt \verb-+-$X$ = $Y$}
    \item {\tt $X$ \verb-+- $Y$ = $Z$} 
    \item {\tt $X$ \verb+-+ $Y$ = $Z$} 
    \item {\tt $X$ \verb+*+ $Y$ = $Z$} 
    \item {\tt $X$ \verb+/+ $Y$ = $Z$} 
    \item {\tt $X$ \verb+//+ $Y$ = $Z$} 
    \item \texttt{$X$ div $Y$ = $Z$} 
    \item {\tt $X$ \verb+/<+ $Y$ = $Z$} 
    \item {\tt $X$ \verb+/>+ $Y$ = $Z$} 
    \item {\tt $X$ \verb+**+ $Y$ = $Z$} 
    \item \texttt{$X$ mod $Y$ = $Z$} 
    \item \texttt{$X$ rem $Y$ = $Z$} 
    \item {\tt \verb+~+$X$ = $Y$} 
    \item {\tt $X$ \verb+\/+ $Y$ = $Z$} 
    \item {\tt $X$ \verb+/\+ $Y$ = $Z$} 
    \item {\tt $X$ \verb+^+ $Y$ = $Z$} 
    \item {\tt $X$ \verb+<<+ $Y$ = $Z$} 
    \item {\tt $X$ \verb+>>+ $Y$ = $Z$} 
    \item {\tt $Var$\verb+[+$Index_1$,$\ldots$,$Index_n$\verb+]+}
    \item \texttt{$Goal_1$,$Goal_2$}
    \item \texttt{$Goal_1$ \&\& $Goal_2$}
    \item \texttt{$Goal_1$;$Goal_2$}
    \item \texttt{$Goal_1$ || $Goal_2$}
    \item \texttt{acyclic\_term($Term$)}
    \item \texttt{and\_to\_list($Conj$) = $List$}
    \item \texttt{append($X$,$Y$,$Z$)}  (nondet)
    \item \texttt{append($X$,$Y$,$Z$,$T$)}  (nondet)
    \item \texttt{apply($S$,$Arg_1$,$\ldots$,$Arg_n$) = $Val$}
    \item \texttt{arg($I$,$T$,$A$)}    
    \item \texttt{arity($Struct$) = $Arity$}
    \item \texttt{array($Term$)}
    \item \texttt{ascii\_alpha($Term$)}
    \item \texttt{ascii\_alpha\_digit($Term$)}
    \item \texttt{ascii\_digit($Term$)}
    \item \texttt{ascii\_lowercase($Term$)}
    \item \texttt{ascii\_uppercase($Term$)}
    \item \texttt{atom($Term$)} 
    \item \texttt{atom\_chars($Atm$) = $String$}
    \item \texttt{atom\_codes($Atm$) = $List$} 
    \item \texttt{atomic($Term$)} 
    \item \texttt{attr\_var($Term$)} 
    \item \texttt{avg($ListOrArray$) = $Val$}
    \item \texttt{between($From$,$To$,$X$)} (nondet)
    \item \texttt{between($From$,$Step$,$To$,$X$)} (nondet)    
    \item \texttt{bigint($Term$)}
    \item \texttt{bind\_vars($Term$,$Val$)}
    \item \texttt{call($S$,$Arg_1$,$\ldots$,$Arg_n$)} 
    \item \texttt{call\_cleanup($S$,$Cleanup$)} 
    \item \texttt{catch($S$,$Exception$,$Handler$)} 
    \item \texttt{char($Term$)} 
    \item \texttt{chr($Code$) = $Char$} 
    \item \texttt{clear($Map$)} 
    \item \texttt{compare\_terms($Term_1$,$Term_2$) = $Res$} 
    \item \texttt{compound($Term$)} 
    \item \texttt{copy\_term($Term_1$) = $Term_2$}
    \item \texttt{count\_all($Call$) = $Int$}
    \item \texttt{del($Map$,$Key$)}    
    \item \texttt{delete($List$,$X$) = $ResList$}
    \item \texttt{delete\_all($List$,$X$) = $ResList$}
    \item \texttt{different\_terms($Term_1$,$Term_2$)}
    \item \texttt{digit($Char$)}
    \item \texttt{dvar($Term$)}
    \item \texttt{dvar\_or\_int($Term$)}
    \item \texttt{fail}
    \item \texttt{false}
    \item \texttt{find\_all($Template$,$Call$) = $List$}
    \item \texttt{findall($Template$,$Call$) = $List$}
    \item \texttt{first($Compound$) = $Term$} 
    \item \texttt{flatten($List1$) = $List2$} 
    \item \texttt{float($Term$)} 
    \item \texttt{fold($F$,$ACC$,$List$) = $Res$} 
    \item \texttt{freeze($X$,$Goal$)}
    \item \texttt{functor($T$,$F$,$N$)}
    \item \texttt{get($Map$,$Key$) = $Val$}
    \item \texttt{get($Map$,$Key$,$DefaultVal$)=$Val$} 
    \item \texttt{get\_attr($AttrVar$,$Key$) = $Val$}
    \item \texttt{get\_attr($AttrVar$,$Key$,$DefaultVal$)=$Val$} 
    \item \texttt{get\_global\_map($ID$) = $Map$}
    \item \texttt{get\_global\_map() = $Map$}
    \item \texttt{get\_heap\_map($ID$) = $Map$} 
    \item \texttt{get\_heap\_map() = $Map$} 
    \item \texttt{get\_table\_map($ID$) = $Map$} 
    \item \texttt{get\_table\_map() = $Map$} 
    \item \texttt{ground($Term$)} 
    \item \texttt{handle\_exception($Term$,$Term$)} 
    \item \texttt{has\_key($Map$,$Key$)} 
    \item \texttt{hash\_code($Term$) = $Int$} 
    \item \texttt{head($List$) = $Term$} 
    \item \texttt{heap\_is\_empty($Heap$)}
    \item \texttt{heap\_pop($Heap$) = $Elm$}
    \item \texttt{heap\_push($Heap$,$Elm$)}
    \item \texttt{heap\_size($Heap$) = $Size$}
    \item \texttt{heap\_to\_list($Heap$) = $List$}
    \item \texttt{heap\_top($Heap$) = $Elm$}
    \item \texttt{insert($List$,$Index$,$Elm$) = $ResList$} 
    \item \texttt{insert\_all($List$,$Index$,$AList$) = $ResList$} 
    \item \texttt{insert\_ordered($List$,$Term$) = $R$} 
    \item \texttt{insert\_ordered\_down($List$,$Term$) = $R$} 
    \item \texttt{int($Term$)} 
    \item \texttt{integer($Term$)} 
    \item \texttt{is($T_1$,$T_2$)} 
    \item \texttt{keys($Map$) = $List$} 
    \item \texttt{last($Compound$) = $Term$} 
    \item \texttt{len($Term$) = $Len$} 
    \item \texttt{length($Term$) = $Len$} 
    \item \texttt{list($Term$)} 
    \item \texttt{list\_to\_and($List$) = $Conj$}
    \item \texttt{lowercase($Char$)} 
    \item \texttt{map($Func$,$List1$,$List2$) = $ResList$} 
    \item \texttt{map($FuncOrList$,$ListOrFunc$) = $ResList$} 
    \item \texttt{map($Term$)} 
    \item \texttt{map\_to\_list($Map$) = $List$} 
    \item \texttt{max($ListOrArray$) = $Val$} 
    \item \texttt{max($X$,$Y$) = $Val$} 
    \item \texttt{maxint\_small() = $Int$}
    \item \texttt{maxof($Call$,$Objective$)} 
    \item \texttt{maxof($Call$,$Objective$,$ReportCall$)} 
    \item \texttt{maxof\_inc($Call$,$Objective$)} 
    \item \texttt{maxof\_inc($Call$,$Objective$,$ReportCall$)} 
    \item \texttt{membchk($Term$,$List$)} 
    \item \texttt{member($Term$,$List$)} (nondet)
    \item \texttt{min($ListOrArray$) = $Val$} 
    \item \texttt{min($X$,$Y$) = $Val$} 
    \item \texttt{minint\_small() = $Int$}
    \item \texttt{minof($Call$,$Objective$)} 
    \item \texttt{minof($Call$,$Objective$,$ReportCall$)} 
    \item \texttt{minof\_inc($Call$,$Objective$)} 
    \item \texttt{minof\_inc($Call$,$Objective$,$ReportCall$)} 
    \item \texttt{name($Struct$) = $Name$} 
    \item \texttt{new\_array($D_1$,$\ldots$,$D_n$) = $Arr$} 
    \item \texttt{new\_list($N$) = $List$} 
    \item \texttt{new\_list($N$,$InitVal$) = $List$} 
    \item \texttt{new\_map($Int$,$PairsList$) = $Map$} 
    \item \texttt{new\_map($IntOrPairsList$) = $Map$} 
    \item \texttt{new\_max\_heap($IntOrList$) = $Heap$}
    \item \texttt{new\_min\_heap($IntOrList$) = $Heap$}
    \item \texttt{new\_set($Int$,$ElmsList$) = $Map$} 
    \item \texttt{new\_set($IntOrElmsList$) = $Map$} 
    \item \texttt{new\_struct($Name$,$IntOrList$) = $Struct$} 
    \item \texttt{nonvar($Term$)} 
    \item \texttt{not $Call$}
    \item \texttt{nth($I$,$ListOrArray$,$Val$)} (nondet)
    \item \texttt{number($Term$)} 
    \item \texttt{number\_chars($Num$) = $String$} 
    \item \texttt{number\_codes($Num$) = $List$} 
    \item \texttt{number\_vars($Term$)}
    \item \texttt{number\_vars($Term$,$N_0$) = $N_1$}
    \item \texttt{once $Call$}
    \item \texttt{ord($Char$) = $Int$} 
    \item \texttt{parse\_radix\_string($String$,$Base$) = $Int$}
    \item \texttt{parse\_term($String$) = $Term$}
    \item \texttt{parse\_term($String$,$Term$,$Vars$)}
    \item \texttt{post\_event($X$,$Event$)}
    \item \texttt{post\_event\_any($X$,$Event$)}
    \item \texttt{post\_event\_bound($X$)}
    \item \texttt{post\_event\_dom($X$,$Event$)}
    \item \texttt{post\_event\_ins($X$)}
    \item \texttt{prod($Collection$) = $Val$}
    \item \texttt{put($Map$,$Key$)} 
    \item \texttt{put($Map$,$Key$,$Val$)} 
    \item \texttt{put\_attr($Var$,$Key$)} 
    \item \texttt{put\_attr($Var$,$Key$,$Val$)} 
    \item \texttt{real($Term$)} 
    \item \texttt{reduce($Func$,$List$) = $Res$} 
    \item \texttt{reduce($Func$,$List$,$InitVal$) = $Res$} 
    \item \texttt{remove\_dups($ListOrArray$) = $ResList$} 
    \item \texttt{repeat} (nondet)
    \item \texttt{reverse($ListOrArray$) = $Res$} 
    \item \texttt{second($Compound$) = $Term$} 
    \item \texttt{select($X$,$List$,$ResList$)} (nondet)
    \item \texttt{size($Map$) = $Size$}
    \item \texttt{slice($ListOrArray$,$From$)}
    \item \texttt{slice($ListOrArray$,$From$,$To$)}
    \item \texttt{sort($ListOrArray$) = $Sorted$} 
    \item \texttt{sort($ListOrArray$,$KeyIndex$) = $Sorted$} 
    \item \texttt{sort\_down($ListOrArray$) = $Sorted$} 
    \item \texttt{sort\_down($ListOrArray$,$KeyIndex$) = $Sorted$} 
    \item \texttt{sort\_down\_remove\_dups($ListOrArray$) = $Sorted$} 
    \item \texttt{sort\_down\_remove\_dups($ListOrArray$,$KeyIndex$) = $Sorted$} 
    \item \texttt{sort\_remove\_dups($ListOrArray$) = $Sorted$} 
    \item \texttt{sort\_remove\_dups($ListOrArray$,$KeyIndex$) = $Sorted$} 
    \item \texttt{sorted($ListOrArray$)} 
    \item \texttt{sorted\_down($ListOrArray$)} 
    \item \texttt{string($Term$)} 
    \item \texttt{struct($Term$)} 
    \item \texttt{subsumes($Term_1$,$Term_2$)}
    \item \texttt{sum($Collection$) = $Val$}
    \item \texttt{tail($List$) = $Term$} 
    \item \texttt{throw($E$)}    
    \item \texttt{to\_array($List$) = $Array$} 
    \item \texttt{to\_atom($String$) = $Atom$} 
    \item \texttt{to\_binary\_string($Int$) = $String$}
    \item \texttt{to\_codes($Term$) = $List$}        
    \item \texttt{to\_fstring($Format$,$Args\ldots$) = $String$}
    \item \texttt{to\_hex\_string($Int$) = $String$}    
    \item \texttt{to\_int($NumOrCharOrStr$) = $Int$} 
    \item \texttt{to\_integer($NumOrCharOrStr$) = $Int$} 
    \item \texttt{to\_list($Struct$) = $List$} 
    \item \texttt{to\_lowercase($String$) = $LString$}
    \item \texttt{to\_number($NumOrCharOrStr$) = $Number$}
    \item \texttt{to\_oct\_string($Int$) = $String$}    
    \item \texttt{to\_radix\_string($Int$,$Base$) = $String$}
    \item \texttt{to\_real($NumOrStr$) = $Real$} 
    \item \texttt{to\_string($Term$) = $String$}        
    \item \texttt{to\_uppercase($String$) = $UString$}
    \item \texttt{true}
    \item \texttt{uppercase($Char$)} 
    \item \texttt{values($Map$) = $List$} 
    \item \texttt{var($Term$)} 
    \item \texttt{variant($Term_1$,$Term_2$)}
    \item \texttt{vars($Term$) = $Vars$}
    \item \texttt{zip($List_1$,$List_2$) = $List$} 
    \item \texttt{zip($List_1$,$List_2$,$List_3$) = $List$} 
    \item \texttt{zip($List_1$,$List_2$,$List_3$,$List_4$) = $List$} 
%    \item \texttt{unnumber\_vars($Term_1$) = $Term_2$}
\end{itemize}
\end{scriptsize}
%
\section*{Module \texttt{math} (imported by default)}
\begin{scriptsize}
\begin{itemize}
   \item \texttt{abs($X$) = $Val$} 
   \item \texttt{acos($X$) = $Val$}
   \item \texttt{acosh($X$) = $Val$} 
   \item \texttt{acot($X$) = $Val$}
   \item \texttt{acoth($X$) = $Val$} 
   \item \texttt{acsc($X$) = $Val$} 
   \item \texttt{acsch($X$) = $Val$} 
   \item \texttt{asec($X$) = $Val$}
   \item \texttt{asech($X$) = $Val$} 
   \item \texttt{asin($X$) = $Val$}
   \item \texttt{asinh($X$) = $Val$} 
   \item \texttt{atan($X$) = $Val$}
   \item \texttt{atan2($X$,$Y$) = $Val$}
   \item \texttt{atanh($X$) = $Val$} 
   \item \texttt{ceiling($X$) = $Val$} 
   \item \texttt{cos($X$) = $Val$} 
   \item \texttt{cosh($X$)  = $Val$} 
   \item \texttt{cot($X$) = $Val$}
   \item \texttt{coth($X$)  = $Val$} 
   \item \texttt{csc($X$) = $Val$}
   \item \texttt{csch($X$)  = $Val$} 
   \item \texttt{e() = 2.71828182845904523536} 
   \item \texttt{even($Int$)} 
   \item \texttt{exp($X$) = $Val$} 
   \item \texttt{floor($X$) = $Val$} 
   \item \texttt{frand() = $Val$}
   \item \texttt{frand($Low$,$High$) = $Val$}    
   \item \texttt{gcd($A$,$B$) = $Val$} 
   \item \texttt{log($X$) = $Val$}
   \item \texttt{log(B,$X$) = $Val$} 
   \item \texttt{log10($X$) = $Val$} 
   \item \texttt{log2($X$) = $Val$} 
   \item \texttt{modf($X$) = ($IntVal$,$FractVal$)} 
   \item \texttt{odd($Int$)} 
   \item \texttt{pi() = 3.14159265358979323846} 
   \item \texttt{pow($X$,$Y$) = $Val$}
   \item \texttt{pow\_mod($X$,$Y$,$Z$) = $Val$}
   \item \texttt{prime($Int$)} 
   \item \texttt{primes($Int$) = $List$} 
   \item \texttt{rand\_max() = $Val$} 
   \item \texttt{random = $Val$} 
   \item \texttt{random($Low$,$High$) = $Val$} 
   \item \texttt{random($Seed$) = $Val$} 
   \item \texttt{random2() = $Int$} 
   \item \texttt{round($X$) = $Val$}
   \item \texttt{sec($X$) = $Val$}
   \item \texttt{sech($X$) = $Val$} 
   \item \texttt{sign($X$) = $Val$}  
   \item \texttt{sin($X$) = $Val$} 
   \item \texttt{sinh($X$) = $Val$} 
   \item \texttt{sqrt($X$) = $Val$} 
   \item \texttt{tan($X$) = $Val$}
   \item \texttt{tanh($X$) = $Val$} 
   \item \texttt{to\_degrees($Radian$) = $Degree$} 
   \item \texttt{to\_radians($Degree$) = $Radian$}
   \item \texttt{truncate($X$) = $Val$}  
%   \item \texttt{inf}
%   \item \texttt{acosh($X$) = $Val$}
%   \item \texttt{asinh($X$) = $Val$}
%   \item \texttt{atanh($X$) = $Val$} 
%   \item \texttt{cbrt($X$) = $Val$}
%   \item \texttt{cosh($X$) = $Val$} 
%   \item \texttt{coth($X$) = $Val$}
%   \item \texttt{ninf}
%   \item \texttt{nthrt($N$,$X$) = $Val$}
%   \item \texttt{randrange($From$,$Step$,$To$) = $Val$}  
%   \item \texttt{randrange($From$,$To$) = $Val$}  
%   \item \texttt{sech($X$) = $Val$} 
%   \item \texttt{sinh($X$) = $Val$} 
%   \item \texttt{tanh($X$) = $Val$}
%   \item \texttt{csch($X$) = $Val$}
\end{itemize}
\end{scriptsize}
\section*{Module \texttt{io} (imported by default)}
\begin{scriptsize}
\begin{itemize}
   \item \texttt{at\_end\_of\_stream($FD$)}
   \item \texttt{close($FD$)}
   \item \texttt{flush($FD$)}
   \item \texttt{flush()}
   \item \texttt{nl($FD$)}
   \item \texttt{nl()}
   \item \texttt{open($Name$) = $FD$}
   \item \texttt{open($Name$,$Mode$) = $FD$}
   \item \texttt{peek\_byte($FD$) = $Val$}
   \item \texttt{peek\_char($FD$) = $Val$}
   \item \texttt{print($FD$,$Term$)}
   \item \texttt{print($Term$)}
   \item \texttt{printf($FD$,$Format$,$Args\ldots$)}
   \item \texttt{println($FD$,$Term$)}
   \item \texttt{println($Term$)}
   \item \texttt{read\_atom($FD$) = $Atom$}
   \item \texttt{read\_atom() = $Atom$}
   \item \texttt{read\_byte($FD$) = $Val$}
   \item \texttt{read\_byte($FD$,$N$) = $List$}
   \item \texttt{read\_byte() = $Val$}
   \item \texttt{read\_char($FD$) = $Val$}
   \item \texttt{read\_char($FD$,$N$) = $String$}
   \item \texttt{read\_char() = $Val$}
   \item \texttt{read\_char\_code($FD$) = $Val$}
   \item \texttt{read\_char\_code($FD$,$N$) = $List$}
   \item \texttt{read\_char\_code() = $Val$}
   \item \texttt{read\_file\_bytes($File$) = $List$}
   \item \texttt{read\_file\_bytes() = $List$}
   \item \texttt{read\_file\_chars($File$) = $String$}
   \item \texttt{read\_file\_chars() = $String$}
   \item \texttt{read\_file\_codes($File$) = $List$}
   \item \texttt{read\_file\_codes() = $List$}
   \item \texttt{read\_file\_lines($File$) = $List$}
   \item \texttt{read\_file\_lines() = $List$}
   \item \texttt{read\_file\_terms($File$) = $List$}
   \item \texttt{read\_file\_terms() = $List$}
   \item \texttt{read\_int($FD$) = $Int$}
   \item \texttt{read\_int() = $Int$}
   \item \texttt{read\_line($FD$) = $String$}
   \item \texttt{read\_line() = $String$}
   \item \texttt{read\_number($FD$) = $Number$}
   \item \texttt{read\_number() = $Number$}
   \item \texttt{read\_picat\_token($FD$) = $TokenValue$}
   \item \texttt{read\_picat\_token($FD$,$TokenType$,$TokenValue$)}
   \item \texttt{read\_picat\_token($TokenType$,$TokenValue$)}
   \item \texttt{read\_picat\_token() = $TokenValue$}
   \item \texttt{read\_real($FD$) = $Real$}
   \item \texttt{read\_real() = $Real$}
   \item \texttt{read\_term($FD$) = $Term$}
   \item \texttt{read\_term() = $Term$}
   \item \texttt{readln($FD$) = $String$}
   \item \texttt{readln() = $String$}
   \item \texttt{write($FD$,$Term$)}
   \item \texttt{write($Term$)}
   \item \texttt{write\_byte($Bytes$)}
   \item \texttt{write\_byte($FD$,$Bytes$)}
   \item \texttt{write\_char($Chars$)}
   \item \texttt{write\_char($FD$,$Chars$)}
   \item \texttt{write\_char\_code($Codes$)}
   \item \texttt{write\_char\_code($FD$,$Codes$)}
   \item \texttt{writef($FD$,$Format$,$Args\ldots$)}
   \item \texttt{writeln($FD$,$Term$)}
   \item \texttt{writeln($Term$)}
\end{itemize}
\end{scriptsize}
\section*{Module \texttt{ordset}}
\begin{scriptsize}
\begin{itemize}
\item \texttt{delete($OSet$,$Elm$) = $OSet1$}
\item \texttt{disjoint($OSet1$,$OSet2$)}
\item \texttt{insert($OSet$,$Elm$) = $OSet1$}
\item \texttt{intersection($OSet1$,$OSet2$)=$OSet3$}
\item \texttt{new\_ordset($List$)}
\item \texttt{ordset($Term$)}
\item \texttt{subset($OSet1$,$OSet2$)}
\item \texttt{subtract($OSet1$,$OSet2$)=$OSet3$}
\item \texttt{union($OSet1$,$OSet2$)=$OSet3$}
\end{itemize}
\end{scriptsize}
\section*{Module \texttt{os}}
\begin{scriptsize}
\begin{itemize}
\item \texttt{cd($Path$)}
\item \texttt{chdir($Path$)}
\item \texttt{cp($FromPath$,$ToPath$)}
\item \texttt{cwd() = $Path$}
\item \texttt{directory($Path$)}
\item \texttt{dir}
\item \texttt{env\_exists($Name$)}
\item \texttt{executable($Path$)}
\item \texttt{exists($Path$)}
\item \texttt{file($Path$)}
\item \texttt{file\_base\_name($Path$) = $String$}
\item \texttt{file\_directory\_name($Path$) = $String$}
\item \texttt{file\_exists($Path$)}
\item \texttt{getenv($EnvString$) = $String$}
\item \texttt{listdir($Path$) = $List$}
\item \texttt{ls}
\item \texttt{mkdir($Path$)}
\item \texttt{pwd() = $Path$}
\item \texttt{readable($Path$)}
\item \texttt{rename($Old$,$New$)}
\item \texttt{rm($Path$)}
\item \texttt{rmdir($Path$)}
\item \texttt{separator() = $Val$}
\item \texttt{size($Path$) = $Int$}
\item \texttt{writable($Path$)}
\ignore{
\item \texttt{atime($Path$) = $DateTime$}
\item \texttt{block\_special($Path$)}
\item \texttt{char\_special($Path$)}
\item \texttt{chmod($Path$,$Mode$)}
\item \texttt{create($Path$)}
\item \texttt{create($Path$,$Mode$)}
\item \texttt{ctime($Path$) = $DateTime$}
\item \texttt{dev\_id($Path$) = $Int$}
\item \texttt{directory\_exists($Path$)}
\item \texttt{fifo($Path$)}
\item \texttt{file\_type($Path$) = $Term$}
\item \texttt{gid($Path$) = $Int$}
\item \texttt{ino($Path$) = $Int$}
\item \texttt{link($Path$)}
\item \texttt{link($Path1$,$Path2$)}
\item \texttt{listdir($Path$,$REPattern$) = $List$}
\item \texttt{message\_queue($Path$)}
\item \texttt{mkdir($Path$,$Mode$)}
\item \texttt{mkdirs($Path$)}
\item \texttt{mkdirs($Path$,$Mode$)}
\item \texttt{mode($Path$) = $String$}
\item \texttt{mode($Path$,$Value$)}
\item \texttt{mtime($Path$) = $DateTime$}
\item \texttt{mv($Path1$,$Path2$)}
\item \texttt{nlink($Path$) = $Int$}
\item \texttt{root() = $Path$}
\item \texttt{semaphore($Path$)}
\item \texttt{shared\_memory($Path$)}
\item \texttt{shortcut($Path$)}
\item \texttt{shortcut($Path1$,$Path2$)}
\item \texttt{socket($Path$)}
\item \texttt{uid($Path$) = $Int$}
\item \texttt{unlink($Path$)}
}
\end{itemize}
\end{scriptsize}
\section*{Modules \texttt{cp}, \texttt{mip}, \texttt{sat}, and \texttt{smt}}
\begin{scriptsize}
\begin{itemize}
    \item {\tt \verb+#~+$X$}
    \item {\tt $X$ \verb+#!=+ $Y$} 
    \item {\tt $X$ \verb+#/\+ $Y$}
    \item {\tt $X$ \verb+#<+ $Y$} 
    \item {\tt $X$ \verb+#<=+ $Y$}
    \item {\tt $X$ \verb+#<=>+ $Y$}
    \item {\tt $X$ \verb+#=+ $Y$} 
    \item {\tt $X$ \verb+#=<+ $Y$} 
    \item {\tt $X$ \verb+#=>+ $Y$}
    \item {\tt $X$ \verb+#>+ $Y$} 
    \item {\tt $X$ \verb+#>=+ $Y$} 
    \item {\tt $X$ \verb+#\/+ $Y$}
    \item {\tt $X$ \verb+#^+ $Y$}
\item \texttt{$Vars$ :: $Exp$}
\item \texttt{$Vars$ notin $Exp$}
\item \texttt{acyclic($Vs$,$Es$)}
\item \texttt{acyclic\_d($Vs$,$Es$)}
\item \texttt{all\_different($FDVars$)}
\item \texttt{all\_different\_except\_0($FDVars$)}
\item \texttt{all\_distinct($FDVars$)}
\item \texttt{assignment($FDVars1$,$FDVars2$)}
\item \texttt{at\_least($N$,$L$,$V$)}
\item \texttt{at\_most($N$,$L$,$V$)} 
\item \texttt{bv\_add($A$,$B$,$C$)} (sat only)
\item \texttt{bv\_and($A$,$B$,$C$)} (sat only)
\item \texttt{bv\_div($A$,$B$,$C$)} (sat only)
\item \texttt{bv\_drop($A$,$N$)} (sat only)
\item \texttt{bv\_eq($A$,$B$)} (sat only)
\item \texttt{bv\_ge($A$,$B$)} (sat only)
\item \texttt{bv\_gt($A$,$B$)} (sat only)
\item \texttt{bv\_mod($A$,$B$,$C$)} (sat only)
\item \texttt{bv\_mul($A$,$B$,$C$)} (sat only)
\item \texttt{bv\_neq($A$,$B$)} (sat only)
\item \texttt{bv\_or($A$,$B$,$C$)} (sat only)
\item \texttt{bv\_pow($A$,$B$,$C$)} (sat only)
\item \texttt{bv\_sum($As$,$B$)} (sat only)
\item \texttt{bv\_take($A$,$N$)} (sat only)
\item \texttt{bv\_to\_int($A$)} (sat only)
\item \texttt{bv\_xor($A$,$B$,$C$)} (sat only)
\item \texttt{circuit($FDVars$)}
\item \texttt{count($V$,$FDVars$,$N$)}
\item \texttt{count($V$,$FDVars$,$Rel$,$N$)}
\item \texttt{cumulative($Ss$,$Ds$,$Rs$,$Limit$)}
\item \texttt{decreasing($L$)}
\item \texttt{decreasing\_strict($L$)}
\item \texttt{diffn($RectangleList$)}
\item \texttt{disjunctive\_tasks($Tasks$)} (cp only)
\item \texttt{element($I$,$List$,$V$)}
\item \texttt{element0($I$,$List$,$V$)}
\item \texttt{exactly($N$,$L$,$V$)}
\item \texttt{fd\_degree($FDVar$) = $Degree$} (cp only)
\item \texttt{fd\_disjoint($DVar1$,$DVar2$)} 
\item \texttt{fd\_dom($FDVar$) = $List$}
\item \texttt{fd\_false($FDVar$,$Elm$)}
\item \texttt{fd\_max($FDVar$) = $Max$}
\item \texttt{fd\_min($FDVar$) = $Min$}
\item \texttt{fd\_min\_max($FDVar$,$Min$,$Max$)}
\item \texttt{fd\_next($FDVar$,$Elm$) = $NextElm$}
\item \texttt{fd\_prev($FDVar$,$Elm$) = $PrevElm$}
\item \texttt{fd\_set\_false($FDVar$,$Elm$)} (cp only)
\item \texttt{fd\_size($FDVar$) = $Size$}
\item \texttt{fd\_true($FDVar$,$Elm$)}
\item \texttt{fd\_vector\_min\_max($Min$,$Max$)}
\item \texttt{global\_cardinality($List$,$Pairs$)}
\item \texttt{hcp($Vs$,$Es$)}
\item \texttt{hcp($Vs$,$Es$,$K$)}
\item \texttt{hcp\_grid($A$)}
\item \texttt{hcp\_grid($A$,$Es$)}
\item \texttt{hcp\_grid($A$,$Es$,$K$)}
\item \texttt{increasing($L$)}
\item \texttt{increasing\_strict($L$)}
\item \texttt{indomain($Var$)} (nondet) (cp only)
\item \texttt{indomain\_down($Var$)} (nondet) (cp only)
\item \texttt{int\_to\_bv($C$)} (sat only)
\item \texttt{lex\_le($L_1$,$L_2$)}
\item \texttt{lex\_lt($L_1$,$L_2$)}
\item \texttt{matrix\_element($Matrix$,$I$,$J$,$V$)}
\item \texttt{matrix\_element0($Matrix$,$I$,$J$,$V$)}
\item \texttt{neqs($NeqList$)} (cp only)
\item \texttt{new\_bv($N$)} (sat only)
\item \texttt{new\_dvar() = $FDVar$}
\item \texttt{new\_fd\_var() = $FDVar$}
\item \texttt{path($Vs$,$Es$,$Src$,$Dest$)}
\item \texttt{path\_d($Vs$,$Es$,$Src$,$Dest$)}
\item \texttt{regular$(X,Q,S,D,Q0,F)$}
\item \texttt{scalar\_product($A$,$X$,$Product$)} 
\item \texttt{scalar\_product($A$,$X$,$Rel$,$Product$)}
\item \texttt{scc($Vs$,$Es$)}
\item \texttt{scc($Vs$,$Es$,$K$)}
\item \texttt{scc\_d($Vs$,$Es$)}
\item \texttt{scc\_d($Vs$,$Es$,$K$)}
\item \texttt{scc\_grid($A$)}
\item \texttt{scc\_grid($A$,$K$)}
\item \texttt{serialized($Starts$,$Durations$)}
\item \texttt{solve($Opts$,$Vars$)} (nondet)
\item \texttt{solve($Vars$)} (nondet)
\item \texttt{solve\_all($Opts$,$Vars$) = $List$}
\item \texttt{solve\_all($Vars$) = $List$}
\item \texttt{solve\_suspended($Opt$)} (cp only)
\item \texttt{solve\_suspended} (cp only)
\item \texttt{subcircuit($FDVars$)}
\item \texttt{subcircuit\_grid($A$)}
\item \texttt{subcircuit\_grid($A$,$K$)}
\item \texttt{table\_in($DVars$,$R$)}
\item \texttt{table\_notin($DVars$,$R$)}
\item \texttt{tree($Vs$,$Es$)}
\item \texttt{tree($Vs$,$Es$,$K$)}

\end{itemize}
\end{scriptsize}
\section*{Module \texttt{planner}}  
\begin{scriptsize}
\begin{itemize}
\item \texttt{best\_plan($S$,$Limit$,$Plan$)}
\item \texttt{best\_plan($S$,$Limit$,$Plan$,$Cost$)}
\item \texttt{best\_plan($S$,$Plan$)}
\item \texttt{best\_plan($S$,$Plan$,$Cost$)}
\item \texttt{best\_plan\_bb($S$,$Limit$,$Plan$)}
\item \texttt{best\_plan\_bb($S$,$Limit$,$Plan$,$Cost$)}
\item \texttt{best\_plan\_bb($S$,$Plan$)}
\item \texttt{best\_plan\_bb($S$,$Plan$,$Cost$)}
\item \texttt{best\_plan\_bin($S$,$Limit$,$Plan$)}
\item \texttt{best\_plan\_bin($S$,$Limit$,$Plan$,$Cost$)}
\item \texttt{best\_plan\_bin($S$,$Plan$)}
\item \texttt{best\_plan\_bin($S$,$Plan$,$Cost$)}
\item \texttt{best\_plan\_nondet($S$,$Limit$,$Plan$)} (nondet)
\item \texttt{best\_plan\_nondet($S$,$Limit$,$Plan$,$Cost$)} (nondet)
\item \texttt{best\_plan\_nondet($S$,$Plan$)} (nondet)
\item \texttt{best\_plan\_nondet($S$,$Plan$,$Cost$)} (nondet)
\item \texttt{best\_plan\_unbounded($S$,$Limit$,$Plan$)}
\item \texttt{best\_plan\_unbounded($S$,$Limit$,$Plan$,$Cost$)}
\item \texttt{best\_plan\_unbounded($S$,$Plan$)}
\item \texttt{best\_plan\_unbounded($S$,$Plan$,$Cost$)}
\item \texttt{current\_plan()=$Plan$}
\item \texttt{current\_resource()=$Amount$}
\item \texttt{current\_resource\_plan\_cost($Amount$,$Plan$,$Cost$)}
\item \texttt{is\_tabled\_state($S$)}
\item \texttt{plan($S$,$Limit$,$Plan$)}
\item \texttt{plan($S$,$Limit$,$Plan$,$Cost$)}
\item \texttt{plan($S$,$Plan$)}
\item \texttt{plan($S$,$Plan$,$Cost$)}
\item \texttt{plan\_unbounded($S$,$Limit$,$Plan$)}
\item \texttt{plan\_unbounded($S$,$Limit$,$Plan$,$Cost$)}
\item \texttt{plan\_unbounded($S$,$Plan$)}
\item \texttt{plan\_unbounded($S$,$Plan$,$Cost$)}
\end{itemize}
\end{scriptsize}
\section*{Module \texttt{nn} (Neural Networks)}
\begin{scriptsize}
\begin{itemize}
\item \texttt{new\_nn($Layers$) = $NN$}
\item \texttt{new\_sparse\_nn($Layers$) = $NN$}
\item \texttt{new\_sparse\_nn($Layers$,$Rate$) = $NN$}
\item \texttt{new\_standard\_nn($Layers$) = $NN$}
\item \texttt{nn\_destroy($NN$)}
\item \texttt{nn\_destroy\_all}
\item \texttt{nn\_load($File$) = $NN$}
\item \texttt{nn\_print($NN$)}
\item \texttt{nn\_run($NN$,$Input$) = $Output$}
\item \texttt{nn\_run($NN$,$Input$,$Opts$) = $Output$}
\item \texttt{nn\_save($NN$,$File$)}
\item \texttt{nn\_set\_activation\_function\_hidden($NN$,$Func$)}
\item \texttt{nn\_set\_activation\_function\_layer($NN$,$Func$,$Layer$)}
\item \texttt{nn\_set\_activation\_function\_output($NN$,$Func$)}
\item \texttt{nn\_set\_activation\_steepness\_hidden($NN$,$Steepness$)}
\item \texttt{nn\_set\_activation\_steepness\_layer($NN$,$Steepness$,$Layer$)}
\item \texttt{nn\_set\_activation\_steepness\_output($NN$,$Steepness$)}
\item \texttt{nn\_train($NN$,$Data$)}
\item \texttt{nn\_train($NN$,$Data$,$Opts$)}
\item \texttt{nn\_train\_data\_get($Data$,$I$) = $Pair$}
\item \texttt{nn\_train\_data\_load($File$) = $Data$}
\item \texttt{nn\_train\_data\_save($Data$,$File$)}
\item \texttt{nn\_train\_data\_size($Data$) = $Size$}
\end{itemize}
\end{scriptsize}
\section*{Module \texttt{datetime}}  
\begin{scriptsize}
\begin{itemize}
\item \texttt{current\_datetime() = $DateTime$}
\item \texttt{current\_day() = $WDay$}
\item \texttt{current\_date() = $Date$}
\item \texttt{current\_time() = $Time$}
\end{itemize}
\end{scriptsize}
\ignore{
\section*{Module \texttt{thread}}
\begin{scriptsize}
\begin{itemize}
    \item \texttt{acquire\_mutex($Mutex$)}
    \item \texttt{broadcast\_cv($CV$)}
    \item \texttt{join($Thread$)}
    \item \texttt{new\_cv() = $CV$}
    \item \texttt{new\_mutex() = $Mutex$}
    \item \texttt{new\_rwlock() = $RWLock$}
    \item \texttt{new\_semaphore() = $Semaphore$}
    \item \texttt{new\_semaphore($N$) = $Semaphore$}
    \item \texttt{new\_thread($S$,$Arg_1$,$\ldots$,$Arg_n$) = $Thread$}
    \item \texttt{p\_semaphore($Semaphore$)}
    \item \texttt{rdlock($RWLock$)}
    \item \texttt{release\_mutex($Mutex$)}
    \item \texttt{rwunlock($RWLock$)}
    \item \texttt{signal\_cv($CV$)}
    \item \texttt{sleep($Milliseconds$)}
    \item \texttt{start($Thread$)}
    \item \texttt{this\_thread() = $Thread$}
    \item \texttt{v\_semaphore($Semaphore$)}
    \item \texttt{wait\_cv($CV$,$Mutex$)}
    \item \texttt{wrlock($RWLock$)}
\end{itemize}
\end{scriptsize}
\section*{Module \texttt{timer}}
\begin{scriptsize}
\begin{itemize}
    \item \texttt{get\_interval($Timer$) = $Milliseconds$}
    \item \texttt{kill($Timer$)}
    \item \texttt{new\_timer($Milliseconds$) = $Timer$}
    \item \texttt{set\_interval($Timer$,$Milliseconds$)}
    \item \texttt{start($Timer$)}
    \item \texttt{stop($Timer$)}
\end{itemize}
\end{scriptsize}
\section*{Module \texttt{process}}
\begin{scriptsize}
\begin{itemize}
    \item \texttt{exec($S$,$Arg_1$,$\ldots$,$Arg_n$)}
    \item \texttt{execl($S$,$ArgList$)}
    \item \texttt{fork() = $ID$}
    \item \texttt{new\_process($S$,$Arg_1$,$\ldots$,$Arg_n$) = $ID$}
    \item \texttt{pid() = $ID$}
    \item \texttt{ppid() = $ID$}
    \item \texttt{wait() = $StatMap$}
    \item \texttt{waitpid($ID$) = $StatMap$}
\end{itemize}
\end{scriptsize}
\section*{Module \texttt{socket}}
\begin{scriptsize}
\begin{itemize}
    \item \texttt{accept($FD$) = $Client$}
    \item \texttt{bind($FD$,$INet$,$Address$,$Port$)}
    \item \texttt{bind($FD$,$Unix$,$Name$)}
    \item \texttt{close($FD$)}
    \item \texttt{connect($FD$,$INet$,$Address$,$Port$)}
    \item \texttt{connect($FD$,$Unix$,$Name$)}
    \item \texttt{getaddr($Name$) = $Addr$}
    \item \texttt{getcanonicalname($Addr$) = $Name$}
    \item \texttt{gethostbyaddr($Addr$) = $Host$}
    \item \texttt{gethostbyname($Name$) = $Host$}
    \item \texttt{getservbyname($Name$) = $Service$}
    \item \texttt{getservbyname($Name$,$Type$) = $Service$}
    \item \texttt{getservport($Name$) = $Port$}
    \item \texttt{getsockopt($FD$,$Level$,$Option$) = $Value$}
    \item \texttt{joingroup($GroupAddress$)}
    \item \texttt{leavegroup($GroupAddress$)}
    \item \texttt{listen($FD$)}
    \item \texttt{listen($FD$,$Backlog$)}
    \item \texttt{recv($FD$) = $Message$}
    \item \texttt{recv($FD$,$Flags$) = $Message$}
    \item \texttt{recvfrom($FD$,$Domain$) = $Message$}
    \item \texttt{recvfrom($FD$,$Flags$,$Domain$) = $Message$}
    \item \texttt{send($FD$,$Message$) = $NBytes$}
    \item \texttt{send($FD$,$Message$,$Flags$) = $NBytes$}
    \item \texttt{sendto($FD$,$Message$,$Domain$,$Address$,$Port$) = $NBytes$}
    \item \texttt{sendto($FD$,$Message$,$Flags$,\\        $Domain$,$Address$,$Port$) = $NBytes$}
    \item \texttt{sendto($FD$,$Message$,$Flags$,$Name$) = $NBytes$}
    \item \texttt{sendto($FD$,$Message$,$Name$) = $NBytes$}
    \item \texttt{setsockopt($FD$,$Level$,$Option$,$Value$)}
    \item \texttt{socket($Domain$,$Type$) = $FD$}
    \item \texttt{tcp\_bind($FD$,$Address$,$Port$)}
    \item \texttt{tcp\_connect($FD$,$Address$,$Port$)}
    \item \texttt{tcp\_socket() = $FD$}
    \item \texttt{udp\_bind($FD$,$Address$,$Port$)}
    \item \texttt{udp\_socket() = $FD$}
    \item \texttt{unix\_bind($FD$,$Name$)}
    \item \texttt{unix\_connect($FD$,$Name$)}
    \item \texttt{unix\_socket() = $FD$}
\end{itemize}
\end{scriptsize}
}
\section*{Module \texttt{sys} (imported by default)}
\begin{scriptsize}
\begin{itemize}
    \item \texttt{abort}
    \item \texttt{cl}
    \item \texttt{cl($File$)}
    \item \texttt{cl\_facts($Facts$)}
    \item \texttt{cl\_facts($Facts$,$IndexInfo$)}    
    \item \texttt{cl\_facts\_table($Facts$)}
    \item \texttt{cl\_facts\_table($Facts$,$IndexInfo$)}
    \item \texttt{command($String$)}
    \item \texttt{compile($File$)}
    \item \texttt{debug}
    \item \texttt{exit} 
    \item \texttt{garbage\_collect} 
    \item \texttt{garbage\_collect(Size)} 
    \item \texttt{halt} 
    \item \texttt{initialize\_table}
    \item \texttt{load($File$)}
    \item \texttt{loaded\_modules()}
    \item \texttt{nodebug}
    \item \texttt{nospy}
    \item \texttt{notrace}
    \item \texttt{spy $Functor$}
    \item \texttt{statistics}
    \item \texttt{statistics($Name$,$Value$)} (nondet)
    \item \texttt{statistics\_all() = $List$}    
    \item \texttt{time($Goal$)}
    \item \texttt{time2($Goal$)} 
    \item \texttt{time\_out($Goal$,$Limit$,$Res$)}
    \item \texttt{trace}
%    \item \texttt{execute($CommandString$) = $Status$}
%    \item \texttt{exit}
%    \item \texttt{help}
%    \item \texttt{modules() = $List$}
%    \item \texttt{profile($Goal$)}
%    \item \texttt{profile\_src($File$)}
%    \item \texttt{prompt($NewPrompt$)}
%    \item \texttt{table\_get\_all($Goal$) = $List$}
%    \item \texttt{table\_get\_one($Goal$)}
\end{itemize}
\end{scriptsize}
\section*{Module \texttt{util}}
\begin{scriptsize}
\begin{itemize}
%    \item \texttt{ = } 
    \item \texttt{array\_matrix\_to\_list($Matrix$) = $List$}
    \item \texttt{array\_matrix\_to\_list\_matrix($AMatrix$) = $LMatrix$}
    \item \texttt{chunks\_of($List$,$K$) = $ListOfLists$}
    \item \texttt{find($String$,$SubString$,$From$,$To$)} (nondet)
    \item \texttt{find\_first\_of($Term$,$Pattern$) = $Index$}
    \item \texttt{find\_ignore\_case($String$,$SubString$,$From$,$To$)} (nondet)
    \item \texttt{find\_last\_of($Term$,$Pattern$) = $Index$}
    \item \texttt{join($Words$) = $String$}
    \item \texttt{join($Words$,$Separator$) = $String$}
    \item \texttt{list\_matrix\_to\_array\_matrix($LMatrix$) = $AMatrix$} 
    \item \texttt{lstrip($List$) = $List$ }
    \item \texttt{lstrip($List$,$Elms$) = $List$ }
    \item \texttt{matrix\_multi($MatrixA$,$MatrixB$) = $MatrixC$}
    \item \texttt{permutation($List$,$Perm$)} (nondet)
    \item \texttt{permutations($List$) = $Lists$}
    \item \texttt{power\_set($List$) = $Lists$}
    \item \texttt{replace($Term$,$Old$,$New$) = $NewTerm$}
    \item \texttt{replace\_at($Term$,$Index$,$New$) = $NewTerm$}
    \item \texttt{rstrip($List$) = $List$ } 
    \item \texttt{rstrip($List$,$Elms$) = $List$ }
    \item \texttt{split($List$) = $Words$ } 
    \item \texttt{split($List$,$Separators$) = $Words$ }
    \item \texttt{strip($List$) = $List$ }
    \item \texttt{strip($List$,$Elms$) = $List$ } 
    \item \texttt{take($List$,$K$) = $List$} 
    \item \texttt{transpose($Matrix$) = $Transposed$}
\end{itemize}
\end{scriptsize}
\ignore{
\section*{Module \texttt{datetime}}
\begin{scriptsize}
\begin{itemize}
    \item \texttt{add\_days($DateTime$,$Days$) = $DateTime$}
    \item \texttt{add\_hours($DateTime$,$Hours$) = $DateTime$}
    \item \texttt{add\_milliseconds($DateTime$,$MilliSeconds$) = $DateTime$}
    \item \texttt{add\_minutes($DateTime$,$Minutes$) = $DateTime$}
    \item \texttt{add\_months($DateTime$,$Months$) = $DateTime$}
    \item \texttt{add\_seconds($DateTime$,$Seconds$) = $DateTime$}
    \item \texttt{add\_years($DateTime$,$Years$) = $DateTime$}
    \item \texttt{compare($DateTime$,$DateTime$) = $Res$}
    \item \texttt{current\_datetime() = $DateTime$}
    \item \texttt{day($DateTime$) = $Day$}
    \item \texttt{day\_of\_week($DateTime$) = $Atom$}
    \item \texttt{day\_of\_year($DateTime$) = $Int$}
    \item \texttt{day\_string($DateTime$) = $String$}
    \item \texttt{dt\_to\_fstring($Format$,$DateTime$) = $String$}
    \item \texttt{hour($DateTime$) = $Hour$}
    \item \texttt{is\_leap\_year($DateTime$)}
    \item \texttt{millisecond($DateTime$) = $MilliSecond$}
    \item \texttt{minute($DateTime$) = $Minute$}
    \item \texttt{month($DateTime$) = $Month$}
    \item \texttt{month\_string($DateTime$) = $String$}
    \item \texttt{second($DateTime$) = $Second$}
    \item \texttt{set\_day($DateTime$,$Day$)}
    \item \texttt{set\_hour($DateTime$,$Hour$)}
    \item \texttt{set\_millisecond($DateTime$,$MilliSecond$)}
    \item \texttt{set\_minute($DateTime$,$Minute$)}
    \item \texttt{set\_month($DateTime$,$Month$)}
    \item \texttt{set\_second($DateTime$,$Second$)}
    \item \texttt{set\_year($DateTime$,$Year$)}
    \item \texttt{time\_string($DateTime$) = $String$}
    \item \texttt{year($DateTime$) = $Year$}
\end{itemize}
\end{scriptsize}
}
\end{multicols}
\ignore{
\end{document}
}
\end{adjustwidth}
\clearpage
\phantomsection
\addcontentsline{toc}{chapter}{Index}
\printindex
\end{document}
