1% BEGIN LICENSE BLOCK
2% Version: CMPL 1.1
3%
4% The contents of this file are subject to the Cisco-style Mozilla Public
5% License Version 1.1 (the "License"); you may not use this file except
6% in compliance with the License.  You may obtain a copy of the License
7% at www.eclipse-clp.org/license.
8% 
9% Software distributed under the License is distributed on an "AS IS"
10% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See
11% the License for the specific language governing rights and limitations
12% under the License. 
13% 
14% The Original Code is  The ECLiPSe Constraint Logic Programming System. 
15% The Initial Developer of the Original Code is  Cisco Systems, Inc. 
16% Portions created by the Initial Developer are
17% Copyright (C) 2006 Cisco Systems, Inc.  All Rights Reserved.
18% 
19% Contributor(s): 
20% 
21% END LICENSE BLOCK
22
23\chapter{\eclipse{} Programming}
24%HEVEA\cutdef[1]{section}
25
26%----------------------------------------------------------------------
27\section{Structure Notation}
28\label{structures}
29In \eclipse, structure fields can be given names.
30This makes it possible to write structures in a
31more readable and maintainable way.
32Such structures first need to be declared by specifying a template like:   
33\begin{code}
34:- local struct( book(author, title, year, publisher) ).
35\end{code}
36Structures with the functor book/4 can then be written as   
37\begin{quote}\begin{verbatim}
38book{}
39book{title:'tom sawyer'}
40book{title:'tom sawyer', year:1876, author:twain}
41\end{verbatim}\end{quote}
42which, in canonical syntax, correspond to the following:
43\begin{quote}\begin{verbatim}
44book(_, _, _, _)
45book(_, 'tom sawyer', _, _)
46book(twain, 'tom sawyer', 1876, _)
47\end{verbatim}\end{quote}
48There is absolutely no semantic difference between the two syntactical forms.
49The special struct-syntax with names has the advantage that
50\begin{itemize}
51\item the arguments can be written in any order
52\item ``dummy'' arguments with anonymous variables do not need to be written
53\item the arity of the structure is not implied (and can be changed
54by changing the declaration and recompiling the program)
55\end{itemize}
56Sometimes it is necessary to refer to the numerical position of a
57structure field within the structure, e.g. in the arg/3 predicate:
58\begin{quote}\begin{verbatim}
59arg(3, B, Y)
60\end{verbatim}\end{quote}
61When the structure has been declared as above, we can write instead:
62\begin{quote}\begin{verbatim}
63arg(year of book, B, Y)
64\end{verbatim}\end{quote}
65
66Declared structures help readability, and make programs easier to modify.
67In order not to lose these benefits, one should always use curly-bracket and
68of-syntax when working with them, and never write them in canonical
69syntax or referring to argument positions numerically.
70
71\See{See also the
72\bipref{update_struct/4}{../bips/kernel/termmanip/update_struct-4.html}
73built-in predicate.}
74
75
76%----------------------------------------------------------------------
77\section{Loops}
78\label{sec:loops}
79To reduce the need for auxiliary recursive predicates, \eclipse{} allows
80the use of an iteration construct
81\begin{quote}\begin{verbatim}
82( IterationSpecs do Goals )
83\end{verbatim}\end{quote}
84Typical applications are: Iteration over a list
85\begin{quote}\begin{verbatim}
86?- ( foreach(X,[1,2,3]) do writeln(X) )
871
882
893
90Yes (0.00s cpu)
91\end{verbatim}\end{quote}
92Process all elements of one list and construct another:
93\begin{quote}\begin{verbatim}
94?- ( foreach(X,[1,2,3]), foreach(Y,List) do Y is X+3 ).
95List = [4, 5, 6]
96Yes (0.00s cpu)
97\end{verbatim}\end{quote}
98Process a list to compute the sum of its elements:
99\begin{quote}\begin{verbatim}
100?- ( foreach(X,[1,2,3]), fromto(0,In,Out,Sum) do Out is In+X ).
101Sum = 6
102Yes (0.00s cpu)
103\end{verbatim}\end{quote}
104Note that the variables X, Y, In and Out are local variables in the loop,
105while the input list and Sum are shared with the context.
106
107If a parameter remains constant across all loop iterations it must
108be specified explicitly (via {\bf param}),
109for example when iterating over an array:
110\begin{quote}\begin{verbatim}
111?- Array = [](4,3,6,7,8),
112   (
113       for(I,1,5),
114       fromto(0,In,Out,Sum),
115       param(Array)
116   do
117       Out is In + Array[I]
118   ).
119\end{verbatim}\end{quote}
120\quickref{Iteration Specifiers for Loops}{
121\begin{description}
122\item[fromto(First,In,Out,Last)]\ \\
123     iterate Goals starting with In=First until Out=Last.
124\item[foreach(X,List)]\ \\
125     iterate Goals with X ranging over all elements of List.
126\item[foreacharg(X,StructOrArray)]\ \\
127     iterate Goals with X ranging over all arguments of StructOrArray.
128\item[foreacharg(X,StructOrArray,Idx)]\ \\
129     same as before, but Idx is set to the argument position of X in
130     StructOrArray.
131\item[foreachelem(X,Array)]\ \\
132     like foreacharg/2, but iterates over all elements of an array
133     of arbitrary dimension.
134\item[foreachelem(X,Array,Idx)]\ \\
135     same as before, but Idx is set to the index position of X in
136     Array.
137\item[foreachindex(Idx,Array)]\ \\ 
138     like foreachelem/3, but returns just the index position and not the
139     element.
140\item[for(I,MinExpr,MaxExpr)]\ \\
141     iterate Goals with I ranging over integers from MinExpr to MaxExpr.
142\item[for(I,MinExpr,MaxExpr,Increment) ]\ \\
143     same as before, but Increment can be specified (it defaults to 1). 
144\item[multifor(List,MinList,MaxList)]\ \\
145     like for/3, but allows iteration over multiple indices (saves
146     writing nested loops).
147\item[multifor(List,MinList,MaxList,IncrementList)]\ \\
148     same as before, but IncrementList can be specified (i.e.\ how
149     much to increment each element of List by).
150\item[count(I,Min,Max)]\ \\
151     iterate Goals with I ranging over integers from Min up to Max.
152\item[param(Var1,Var2,...)]\ \\
153     for declaring variables in Goals global, i.e.\ shared with the context.
154\end{description}
155}
156\See{For details and more examples see the description of the
157\bipref{do/2}{../bips/kernel/control/do-2.html}
158built-in predicate. Additional background can be found in \cite{loops02}.}
159
160%----------------------------------------------------------------------
161
162\section{Working with Arrays of Items}
163
164For convenience, \eclipse{} has some features for facilitating working with
165arrays of items.
166Arrays can be of any dimension, and can be declared with the
167\bipref{dim/2}{../bips/kernel/termmanip/dim-2.html}
168predicate:
169\begin{quote}\begin{verbatim}
170?- dim(M,[3,4]).
171M = []([](_131, _132, _133, _134),
172       [](_126, _127, _128, _129),
173       [](_121, _122, _123, _124))
174yes.
175\end{verbatim}\end{quote}
176\bipref{dim/2}{../bips/kernel/termmanip/dim-2.html} can also be used to
177query the dimensions of an array:
178\begin{quote}\begin{verbatim}
179?- dim(M,[3,4]), dim(M,D).
180...
181D = [3, 4]
182yes.
183\end{verbatim}\end{quote}
184
185\Note{Note that arrays are just structures, and that the functor is not
186important.}
187
188To access a specific element of an array in an expression, specify the index
189list of the desired element, e.g.\
190\begin{quote}\begin{verbatim}
191?- M = []([](2, 3, 5),
192          [](1, 4, 7)),  X is M[1, 2] + M[2, 3].
193X = 10
194M = []([](2, 3, 5), [](1, 4, 7))
195yes.
196\end{verbatim}\end{quote}
197
198\quickref{Array notation}{
199\begin{itemize}
200\item Arrays are just structures
201\item The functor is not important
202\item Declare or query array size with
203        \bipref{dim/2}{../bips/kernel/termmanip/dim-2.html}
204\item Access elements in expressions by specifying their index list
205        (e.g.\ \texttt{A[7]}, \texttt{M[2,3]})
206\item Indices start at 1
207\end{itemize}
208}
209
210\See{For further details see the Array Notation section of the User Manual.}
211
212%----------------------------------------------------------------------
213
214
215\section{Storing Information Across Backtracking}
216
217In pure logic programming, the complete state of a computation is
218reset to an earlier state on backtracking.
219The all-solutions predicates introduced in section \ref{all-solutions}
220provide a way to collect solutions across backtracking.
221
222The following section presents \eclipse's lower-level primitives for storing
223information across failures: bags and shelves.
224Both bags and shelves are referred to by handle, not by name,
225so they make it easy to write robust, reentrant code.
226Bags and shelves disappear when the system backtracks over their
227creation, when the handle gets garbage collected, or when they are
228destroyed explicitly.
229
230
231\subsection{Bags}
232
233A bag is an anonymous object which can be used to store information
234across failures.  A typical application is the collection of
235alternative solutions.
236
237A bag is an unordered collection, referred to by a handle.
238A bag is created using bag_create/1, terms can be added to a bag using
239bag_enter/2, and the whole contents of the bag can be retrieved
240using bag_retrieve/2 or bag_dissolve/2.
241A simple version of the findall/3 predicate from section \ref{all-solutions}
242can be implemented like:
243\begin{code}
244simple_findall(Goal, Solutions) :-
245        bag_create(Bag),
246        (
247            call(Goal),
248            bag_enter(Bag, Goal),
249            fail
250        ;
251            bag_dissolve(Bag, Solutions)
252        ).
253\end{code}
254
255
256\subsection{Shelves}
257
258A shelf is an anonymous object which can be used to store information
259across failures. A typical application is counting of solutions,
260keeping track of the best solution, 
261aggregating information across multiple solutions etc. 
262
263A shelf is an object with multiple slots whose contents survive
264backtracking. The content of each slot can be set and retrieved
265individually, or the whole shelf can be retrieved 
266as a term. Shelves are referred to by a handle.
267
268A shelf is initialized using shelf_create / 2 or shelf_create /
2693. Data is stored in the slots (or the shelf as a whole) with
270shelf_set / 3 and retrieved with shelf_get / 3.  
271
272For example, here is a meta-predicate to count the number of solutions
273to a goal: 
274\begin{code}
275count_solutions(Goal, Total) :-
276    shelf_create(count(0), Shelf),
277    (
278        call(Goal),
279        shelf_get(Shelf, 1, Old),
280        New is Old + 1,
281        shelf_set(Shelf, 1, New),
282        fail
283    ;
284        shelf_get(Shelf, 1, Total)
285    ),
286    shelf_abolish(Shelf).
287\end{code}
288
289
290%----------------------------------------------------------------------
291
292
293%----------------------------------------------------------------------
294\section{Input and Output}
295%----------------------------------------------------------------------
296
297\subsection{Printing {\eclipse} Terms}
298\quickref{Builtins for writing}{
299\begin{description}
300\item[write(+Stream, ?Term)]\ \\
301        write one term in a default format.
302\item[write_term(+Stream, ?Term, +Options)]\ \\
303        write one term, format options can be selected.
304\item[printf(+Stream, +Format, +ArgList)]\ \\
305        write a string with embedded terms, according to a format string.
306\item[writeq(+Stream, ?Term), write_canonical(+Stream, ?Term)]\ \\
307        write one term so that it can be read back.
308\item[put(+Stream, +Char)]\ \\
309        write one character.
310\end{description}
311}
312The predicates of the write-group are generic in the sense that they
313can print any {\eclipse} data structure.
314The different predicates print slightly different formats.
315The {\tt write/1} predicate is intended to be most human-readable, 
316while {\tt writeq/1} is designed so that the
317printed data can be read back by the predicates of the read-family.
318If we print the structured term \verb.foo(3+4, [1,2], X, 'a b', "string").
319the results are as follows:
320\begin{quote}\begin{verbatim}
321write:             foo(3 + 4, [1, 2], X, a b, string)
322writeq:            foo(3 + 4, [1, 2], _102, 'a b', "string")
323\end{verbatim}\end{quote}
324The write-format is the shortest, but some information is missing,
325e.g. that the sequence \verb.a b. is an atomic unit and that \verb.string.
326is a string and not an atom. The writeq-format quotes items properly,
327moreover, the variables are printed with unique numbers, so different
328variables are printed differently and identical ones identically.
329
330Single characters, encoded in ascii, can be output using {\tt put/1},
331for example: 
332\begin{quote}\begin{verbatim} 
333[eclipse: 1] put(97).
334a
335yes.
336\end{verbatim}\end{quote}
337
338\subsection{Reading {\eclipse} Terms}
339\quickref{Builtins for reading}{
340\begin{description}
341\item[read(+Stream, -Term)]\ \\
342        read one fullstop-terminated \eclipse term.
343\item[read_term(+Stream, -Term, +Options)]\ \\
344        read one fullstop-terminated \eclipse term.
345\item[get(+Stream, -Char)]\ \\
346        read one character.
347\item[read_string(+Stream, +Terminator, -Length, -String)]\ \\
348        read a string up to a certain terminator character.
349\item[read_token(+Stream, -Token, -Class)]\ \\
350        read one syntactic token (e.g.\ a number, an atom, a bracket, etc).
351\end{description}
352}
353If the data to be read is in Prolog syntax, it can be read using
354{\tt read(?Term)}.
355This predicate reads one fullstop-terminated
356\eclipse term from stream Stream.
357A fullstop is defined as a dot followed by a layout character like
358blank space or newline.
359Examples:
360\begin{quote}\begin{verbatim}
361[eclipse 4]: read(X).
362 123,a.
363X = 123, a
364yes.
365
366[eclipse 6]: read(X).
367 [3,X,foo(bar),Y].
368X = [3, X, foo(bar), Y]
369yes.
370
371\end{verbatim}\end{quote}
372
373Single characters can be input using {\tt get/1}, which gets their
374ascii encoding, for example:
375\begin{quote}\begin{verbatim} 
376[eclipse: 1] get(X).
377a
378X=97
379yes.
380\end{verbatim}\end{quote}
381
382
383\subsection{Formatted Output}
384The printf-predicate is similar to the printf-function in C, with some
385\eclipse{}-specific format extensions.
386Here are some examples of printing numbers:
387\begin{quote}\begin{verbatim}
388?- printf("%d", [123]).
389123
390yes.
391?- printf("%5d,%05d", [123,456]).
392  123,00456
393yes.
394?- printf("%6.2f", [123]).
395type error in printf("%6.2f", [123])
396?- printf("%6.2f", [123.4]).
397123.40
398yes.
399?- printf("%6.2f", [12.3]).
400 12.30
401yes.
402\end{verbatim}\end{quote}
403The most important \eclipse{}-specific format option is \%w, which
404allows to print like the predicates of the write-family:
405\begin{quote}\begin{verbatim}
406?- printf("%w", [foo(3+4, [1,2], X, 'a b', "string")]).
407foo(3 + 4, [1, 2], X, a b, string)
408\end{verbatim}\end{quote}
409The \%w format allows a number of modifiers in order to access all the
410existing options for the printing of \eclipse{} terms.
411
412\See{For details see the
413\bipref{write_term/2}{../bips/kernel/ioterm/write_term-2.html}
414and
415\bipref{printf/2}{../bips/kernel/ioterm/printf-2.html}
416predicates.}
417
418%----------------------------------------------------------------------
419
420\subsection{Streams}
421
422\eclipse{} I/O is done from and to named channels called streams. 
423The following streams are always opened when \eclipse{} is running:
424{\bf input} (used by the input predicates that do not have
425an explicit stream argument, e.g.\ \bipref{read/1}{../bips/kernel/ioterm/read-1.html}
426\index{read/1}\index{input}),
427{\bf output} (used by the output predicates that do not have
428an explicit stream argument, e.g.\ \bipref{write/1}{../bips/kernel/ioterm/write-1.html}
429\index{write/1}\index{output}),
430{\bf error} (output for error messages and all messages about exceptional states
431\index{error}),
432{\bf warning_output} (used by the system to output warning messages
433\index{warning_output}),
434{\bf log_output} (used by the system to output log messages, e.g.\ messages about garbage
435collection activity
436\index{log_output}),
437{\bf null} (\index{null}
438a dummy stream, output to it is discarded, on input it always
439gives end of file).
440
441Data can be read from a specific stream using
442\biptxtref{read(+Stream,
443?Term)}{read/2}{../bips/kernel/ioterm/read-2.html},
444and written to a specific stream using
445\biptxtref{write(+Stream,
446?Term)}{write/2}{../bips/kernel/ioterm/write-2.html}.
447If no particular stream is specified, input predicates read from {\bf input}
448and output predicates write to {\bf output}.
449
450New streams may be opened onto various I/O devices, see figure \ref{ioopen}.
451\begin{figure}
452\begin{center}
453\begin{tabular}{|c|l|}
454\hline
455I/O device      &       How to open             \\
456\hline
457\hline
458tty             &       implicit (stdin,stdout,stderr) or
459                        \bipref{open/3}{../bips/kernel/iostream/open-3.html} of a device file \\
460\hline
461file            &       \biptxtref{open(FileName, Mode, Stream)}{open/3}{../bips/kernel/iostream/open-3.html}           \\
462\hline
463string          &       \biptxtref{open(string(String), Mode, Stream)}{open/3}{../bips/kernel/iostream/open-3.html}             \\
464\hline
465queue           &       \biptxtref{open(queue(String), Mode, Stream)}{open/3}{../bips/kernel/iostream/open-3.html}              \\
466\hline
467pipe            &       \bipref{exec/2}{../bips/kernel/opsys/exec-2.html},
468                        \bipref{exec/3}{../bips/kernel/opsys/exec-3.html} and
469                        \bipref{exec_group/3}{../bips/kernel/opsys/exec_group-3.html}   \\
470\hline
471socket          &       \bipref{socket/3}{../bips/kernel/iostream/socket-3.html} and
472                        \bipref{accept/3}{../bips/kernel/iostream/accept-3.html}        \\
473\hline
474null            &       implicit (null stream)  \\
475\hline
476\end{tabular}
477\end{center}
478\caption{How to open streams onto the different I/O devices}
479\label{ioopen}
480\end{figure}
481
482All types of streams are closed using
483\biptxtref{close(+Stream)}{close/1}{../bips/kernel/iostream/close-1.html}.
484\See{See the complete description of the
485stream-related built-in predicates in the Reference Manual}
486
487For network communication over sockets, there is a full set of predicates
488modelled after the BSD socket interface:
489\bipref{socket/3}{../bips/kernel/iostream/socket-3.html},
490\bipref{accept/3}{../bips/kernel/iostream/accept-3.html},
491\bipref{bind/2}{../bips/kernel/iostream/bind-2.html},
492\bipref{listen/2}{../bips/kernel/iostream/listen-2.html},
493\bipref{select/3}{../bips/kernel/iostream/select-3.html}.
494See the reference manual for details.
495
496Output in \eclipse{} is usually buffered, i.e.\ printed text goes into
497a buffer and may not immediately appear on the screen, in a file, or
498be sent via a network connection. Use
499\biptxtref{flush(+Stream)}{flush/1}
500{../bips/kernel/iostream/flush-1.html}
501to empty the buffer and write all data to the underlying device.
502
503
504%------------------------------------------------------------------
505
506
507%----------------------------------------------------------------------
508\section{Matching}
509In \eclipse{} you can write clauses that use {\bf matching} (or one-way
510unification) instead of head unification. 
511Such clauses are written with the {\bf ?-} functor instead of {\bf :-}.
512Matching has the property that no variables in the caller will be bound.
513For example
514\begin{code}
515p(f(a,X)) ?- writeln(X).
516\end{code}
517will fail for the following calls:
518\begin{quote}\begin{verbatim}
519?- p(F).
520?- p(f(A,B)).
521?- p(f(A,b)).
522\end{verbatim}\end{quote}
523and succeed (printing b) for
524\begin{quote}\begin{verbatim}
525?- p(f(a,b)).
526\end{verbatim}\end{quote}
527Moreover, the clause
528\begin{code}
529q(X,X) ?- true.
530\end{code}
531will fail for the calls
532\begin{quote}\begin{verbatim}
533?- q(a,b).
534?- q(a,B).
535?- q(A,b).
536?- q(A,B).
537\end{verbatim}\end{quote}
538and succeed for
539\begin{quote}\begin{verbatim}
540?- q(a,a).
541?- q(A,A).
542\end{verbatim}\end{quote}
543
544
545
546%----------------------------------------------------------------------
547\newpage
548\section{List processing}
549%----------------------------------------------------------------------
550
551Lists are probably the most heavily used data structure in Prolog and
552\eclipse{}. Apart from unification/matching, the most commonly used
553list processing predicates are: append/3, length/2, member/2 and sort/2.
554The append/3 predicate can be used to append lists or to split lists:
555\begin{quote}\begin{verbatim}
556?- append([1, 2], [3, 4], L).
557L = [1, 2, 3, 4]
558Yes (0.00s cpu)
559?- append(A, [3, 4], [1, 2, 3, 4]).
560A = [1, 2]
561More (0.00s cpu)
562No (0.01s cpu)
563?- append([1, 2], B, [1, 2, 3, 4]).
564B = [3, 4]
565Yes (0.00s cpu)
566\end{verbatim}\end{quote}
567The length/2 predicate can be used to compute the length of a list
568or to construct a list of a given length:
569\begin{quote}\begin{verbatim}
570?- length([1, 2, 3, 4], N).
571N = 4
572Yes (0.00s cpu)
573?- length(List, 4).
574List = [_1693, _1695, _1697, _1699]
575Yes (0.00s cpu)
576\end{verbatim}\end{quote}
577The member/2 predicate can be used to check membership in a list
578(but memberchk/2 should be preferred for that purpose),
579or to backtrack over all list members:
580\begin{quote}\begin{verbatim}
581?- memberchk(2, [1, 2, 3]).
582Yes (0.00s cpu)
583?- member(X, [1, 2, 3]).
584X = 1
585More (0.00s cpu)
586X = 2
587More (0.01s cpu)
588X = 3
589Yes (0.01s cpu)
590\end{verbatim}\end{quote}
591The sort/2 predicate can sort any list and remove duplicates:
592\begin{quote}\begin{verbatim}
593?- sort([5, 3, 4, 3, 2], Sorted).
594Sorted = [2, 3, 4, 5]
595Yes (0.00s cpu)
596\end{verbatim}\end{quote}
597\See{For more list processing utilities, see the documentation for library(lists).}
598
599
600%----------------------------------------------------------------------
601\section{String processing}
602
603\eclipse{} (unlike many Prolog systems) provides a string data type
604and the corresponding string manipulation predicates, e.g.
605string_length/2, concat_string/2, split_string/4, substring/4,
606and conversion from and to other data types, e.g.
607string_list/2, atom_string/2, number_string/2, term_string/2.
608\begin{quote}\begin{verbatim}
609?- string_length("hello", N).
610N = 5
611Yes (0.00s cpu)
612?- concat_string([abc, 34, d], S).
613S = "abc34d"
614Yes (0.00s cpu)
615?- string_list("hello", L).
616L = [104, 101, 108, 108, 111]
617Yes (0.00s cpu)
618?- term_string(foo(3, bar), S).
619S = "foo(3, bar)"
620Yes (0.00s cpu)
621\end{verbatim}\end{quote}
622
623
624%----------------------------------------------------------------------
625\section{Term processing}
626
627Apart from unification/matching, there are a number of generic built-in
628predicates that work on arbitrary data terms.
629The \verb/=../ predicate converts structures into lists and vice versa:
630\begin{quote}\begin{verbatim}
631?- foo(a, b, c) =.. List.
632List = [foo, a, b, c]
633Yes (0.00s cpu)
634?- Struct =.. [foo, a, b, c].
635Struct = foo(a, b, c)
636Yes (0.00s cpu)
637\end{verbatim}\end{quote}
638The arg/3 predicate extracts an argument from a structure:
639\begin{quote}\begin{verbatim}
640?- arg(2, foo(a, b, c), X).
641X = b
642Yes (0.00s cpu)
643\end{verbatim}\end{quote}
644The functor/3 predicate extracts functor name and arity from a structured term,
645or, conversely, creates a structured term with a given functor name and arity:
646\begin{quote}\begin{verbatim}
647?- functor(foo(a, b, c), N, A).
648N = foo
649A = 3
650Yes (0.00s cpu)
651?- functor(F, foo, 3).
652F = foo(_1696, _1697, _1698)
653Yes (0.00s cpu)
654\end{verbatim}\end{quote}
655The term_variables/2 predicate extracts all variables from an arbitrarily
656complex term:
657\begin{quote}\begin{verbatim}
658?- term_variables(foo(X, 3, Y, X), Vars).
659Vars = [Y, X]
660\end{verbatim}\end{quote}
661The copy_term/2 predicate creates a copy of a term with fresh variables:
662\begin{quote}\begin{verbatim}
663?- copy_term(foo(3, X), Copy).
664Copy = foo(3, _864)
665Yes (0.00s cpu)
666\end{verbatim}\end{quote}
667
668
669%----------------------------------------------------------------------
670\section{Module System}
671\label{secmodules}
672%----------------------------------------------------------------------
673\subsection{Overview}
674The \eclipse{} module system controls the visibility of
675predicate names,
676syntax settings (structures, operators, options, macros),
677and non-logical store names (records, global variables).
678Predicates and syntax items can be declared local or
679they can be exported and imported.
680Store names are always local.
681
682%All of what a module exports can be imported by invoking
683%\begin{quote} \begin{verbatim}
684%:- use_module(a_module).
685%\end{verbatim} \end{quote}
686%or individual predicates can be imported using e.g.
687%\begin{quote} \begin{verbatim}
688%:- import p/3 from a_module.
689%\end{verbatim} \end{quote}
690
691%----------------------------------------------------------------------
692\subsection{Making a Module}
693A source file can be turned into a module by starting it with a 
694module directive. A simple module is:
695\begin{code}
696:- module(greeting).
697:- export hello/0.
698
699hello :-
700        who(X),
701        printf("Hello %w!%n", [X]).
702
703who(world).
704who(friend).
705\end{code}
706This is a module which contains two predicates. One of them, hello/0
707is exported and can be used by other modules. The other, who/1 is
708local and not accessible outside the module.
709
710\subsection{Using a Module}
711There are 3 ways to use hello/0 from another module.
712The first possibility is to import the whole ''greeting'' module.
713This makes everything available that is exported from ''greeting'':
714\begin{code}
715:- module(main).
716:- import greeting.
717
718main :-
719        hello.
720\end{code}
721The second possibility is to selectively only import the hello/0
722predicate:
723\begin{code}
724:- module(main).
725:- import hello/0 from greeting.
726
727main :-
728        hello.
729\end{code}
730The third way is not to import, but to module-qualify the call to hello/0:
731\begin{code}
732:- module(main).
733
734main :-
735        greeting:hello.
736\end{code}
737
738
739\subsection{Qualified Goals}
740
741The module-qualification using \verb.:/2. is also used to resolve
742name conflicts,
743i.e.\ in the case where a predicate of the same name is defined
744in more than one imported module.
745In this case, none of the conflicting
746predicates is imported - an attempt to call the unqualified predicate
747raises an error.
748The solution is to qualify every reference with the module name:
749\begin{quote}\begin{verbatim}
750:- lib(ic).       % exports $>= / 2
751:- lib(eplex).    % exports $>= / 2
752
753    ..., ic:(X $>= Y), ...
754    ..., eplex:(X $>= Y), ...
755\end{verbatim}\end{quote}
756A more unusual feature, which is however very appropriate for
757constraint programming, is the possibility to call several versions
758of the same predicate by specifying several lookup modules:
759\begin{quote}\begin{verbatim}
760    ..., [ic,eplex]:(X $>= Y), ...
761\end{verbatim}\end{quote}
762which has exactly the same meaning as
763\begin{quote}\begin{verbatim}
764    ..., ic:(X $>= Y), eplex:(X $>= Y), ...
765\end{verbatim}\end{quote}
766Note that the modules do not have to be known at compile time, i.e. it
767is allowed to write code like
768\begin{quote}\begin{verbatim}
769    after(X, Y, Solver) :-
770        Solver:(X $>= Y).
771\end{verbatim}\end{quote}
772This is however likely to be less efficient because it prevents
773compile-time optimizations.
774
775
776
777
778\subsection{Exporting items other than Predicates}
779The most commonly exported items, apart from predicates,
780are structure and operator declarations.
781This is done as follows:
782\begin{code}
783:- module(data).
784:- export struct(employee(name,age,salary)).
785:- export op(500, xfx, reports_to).
786...
787\end{code}
788Such declarations can only be imported by importing the whole
789module which exports them, i.e. using {\tt import data.}.
790
791
792\See{For more details see the User Manual chapter on Modules.}
793
794
795%----------------------------------------------------------------------
796
797\section{Exception Handling}
798
799It is sometimes necessary to exit prematurely from an executing
800procedure, for example because some situation was detected which
801makes continuing impossible.
802In this situation, one wants to return to some defined state and
803perform some kind of recovery action.
804This functionality is provided by catch/3 and throw/1
805(formerly known as block/3 and exit_block/1).
806\quickref{Exception Handling}{
807\begin{description}
808\item[catch(Goal, BTag, Recovery)]\ \\
809    like {\tt call(Goal)}, except that in addition a Recovery goal is set up, which
810     can be called by {\tt throw} from anywhere inside the
811     call to Goal. When {\tt throw(ETag)} is called, then if {\tt ETag} 
812     unifies with a {\tt BTag} from an enclosing {\tt block}, the
813     recovery goal associated with that {\tt catch} is called, with the system
814     immediately failing back to where the {\tt catch} was called.  In
815     addition, {\tt ETag} can be used to pass information to the recovery 
816     goal, if {\tt BTag} occurs as an argument of {\tt Recovery}. 
817\item[throw(ETag)]\ \\
818     will transfer control to the innermost enclosing block/3 whose
819     {\tt BTag} argument unifies with {\tt ETag}.
820\end{description}
821}
822By wrapping a predicate call into catch/3, any irregular termination
823can be caught and handled, e.g.
824\begin{code}
825protected_main(X,Y,Z) :-
826    catch(
827        main(X,Y,Z),
828        Problem,
829        printf("Execution of main/3 aborted with %w%n", [Problem])
830    ).
831
832main(X,Y,Z) :-
833    ...,
834    ( test(...) -> ... ; throw(test_failed) ),
835    ...,
836\end{code}
837When built-in predicates raise errors, this results in the predicate
838being exited with the tag \verb.abort., which can also be caught:
839\begin{quote}\begin{verbatim}
840?- catch(X is 1//0, T, true).
841arithmetic exception in //(1, 0, X)
842X = X
843T = abort
844Yes (0.00s cpu)
845\end{verbatim}\end{quote}
846Note that timeouts and stack overflows also lead to exits and can be
847caught this way.
848
849
850%----------------------------------------------------------------------
851%\section{Using the Debugger (2)}
852
853%----------------------------------------------------------------------
854\section{Time and Memory}
855
856\subsection{Timing}
857Timings are available via the built-in predicates
858\bipref{cputime/1}
859and
860\bipref{statistics/2}.
861To obtain the CPU time consumption of a (succeeding) goal, use the scheme
862\begin{quote} \begin{verbatim}
863cputime(StartTime),
864my_goal,
865TimeUsed is cputime-StartTime,
866printf("Goal took %.2f seconds%n", [TimeUsed]).
867\end{verbatim} \end{quote}
868
869\ignore{
870\subsection{Profiling}
871The profiling tool can be used any time with any compiled Prolog code.
872It uses interrupt-driven sampling and is therefore not available
873on all hardware.
874
875When the goal succeeds or fails, the profiler prints so
876and then it prints the statistics about the time spent
877in every encountered procedure:
878\begin{quote} \begin{verbatim}
879[eclipse 5]: profile(boyer).
880rewriting...
881proving...
882goal succeeded
883
884                PROFILING STATISTICS
885                --------------------
886
887Goal:             boyer
888Total user time:  10.65s
889
890Predicate             Module         %Time  Time
891-------------------------------------------------
892rewrite           /2  eclipse        52.3%  5.57s
893garbage_collect   /0  sepia_kernel   23.1%  2.46s
894rewrite_args      /2  eclipse        16.6%  1.77s
895equal             /2  eclipse         4.7%  0.50s
896remainder         /3  eclipse         1.5%  0.16s
897...
898plus              /3  eclipse         0.1%  0.01s
899
900yes.
901\end{verbatim} \end{quote}
902}
903
904%----------------------------------------------------------------------
905%\section{Memory and Garbage collection}
906The
907\bipref{statistics/2}{../bips/kernel/env/statistics-2.html} and \bipref{statistics/0}{../bips/kernel/env/statistics-0.html}
908commands can also be used to obtain memory usage information.
909The memory areas used by \eclipse{} are:
910\begin{description}
911\item[Shared and private heap] for compiled code, non-logical store (
912    bags and shelves, findall)
913    dictionary of functors, various tables and buffers.
914\item[Global stack] for most \eclipse{} data like lists, structures, suspensions.
915        This is likely to be the largest consumer of memory.
916\item[Local stack] for predicate call nesting and local variables.
917\item[Control and trail stack] for data needed on backtracking.
918\end{description}
919Automatic garbage collection is done on the global and trail stack,
920and on the dictionary. Garbage collection parameters can be set using
921\bipref{set_flag/2}{../bips/kernel/env/set_flag-2.html}
922and an explicit collection can be requested using
923\bipref{garbage_collect/0}{../bips/kernel/env/garbage_collect-0.html}.
924
925%----------------------------------------------------------------------
926%\section{Macros}
927%    \subsection{Read/write Macros}
928%    \subsection{Goal Macros}
929
930%----------------------------------------------------------------------
931%\section{Compiler}
932
933%----------------------------------------------------------------------
934\ignore{
935\section{Events}
936
937%\subsection{Event Identifiers}
938Events are identified by names (user defined events)
939or by small numbers (\eclipse{} errors).
940
941%\subsection{Handling Events}
942When an event occurs, a call to the appropriate handler is inserted
943into the resolvent (the sequence of executing goals).
944The handler will be executed as soon as possible, which means at the
945next synchronous point in execution, which is usually just before the
946next regular predicate is invoked.
947
948A handler is defined using a call like this
949\begin{code}
950my_handler(Event) :-
951    <code to deal with Event>
952
953:- set_event_handler(hello, my_handler/1).
954\end{code}
955\index{set_event_handler/2}
956The handler's first argument is the event identifier, in this case the
957atom 'hello'.
958
959%\subsection{Raising Events}
960Events are normally posted to the \eclipse{} engine from its software
961environment, e.g.\ from a C program using
962\begin{quote}\begin{verbatim}
963ec_post_event(ec_atom(ec_did("hello",0)));
964\end{verbatim}\end{quote}
965\index{ec_post_event}
966
967An event can also be raised by the running program itself, using
968\bipref{event/1}{../bips/kernel/event/event-1.html}:
969\begin{quote}\begin{verbatim}
970    ..., event(hello), ...
971\end{verbatim}\end{quote}
972}
973
974\section{Exercises}
975
976\begin{enumerate}
977
978\item
979
980Using a \texttt{do} loop, write a predicate which, when given a 1-d array,
981returns a list containing the elements of the array in reverse order.
982
983
984\item
985
986Write a predicate \texttt{transpose(Matrix, Transpose)} to transpose a 2-d
987array.
988
989Can you make it work backwards?  (i.e.\ if \texttt{Transpose} is specified,
990can you make it return a suitable \texttt{Matrix}?)
991
992\end{enumerate}
993
994%HEVEA\cutend
995