<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.visual-prolog.com/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Kasper+B+H+Petersen</id>
	<title>wiki.visual-prolog.com - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.visual-prolog.com/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Kasper+B+H+Petersen"/>
	<link rel="alternate" type="text/html" href="https://wiki.visual-prolog.com/index.php?title=Special:Contributions/Kasper_B_H_Petersen"/>
	<updated>2026-04-10T02:21:43Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.37.1</generator>
	<entry>
		<id>https://wiki.visual-prolog.com/index.php?title=Exception_Handling&amp;diff=4838</id>
		<title>Exception Handling</title>
		<link rel="alternate" type="text/html" href="https://wiki.visual-prolog.com/index.php?title=Exception_Handling&amp;diff=4838"/>
		<updated>2021-10-13T09:55:32Z</updated>

		<summary type="html">&lt;p&gt;Kasper B H Petersen: /* Introduction to exception handling */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;An exception is a deviation from the expected.  What is an exception in one context may be expected in another context, and thus not an exception in that context.&lt;br /&gt;
&lt;br /&gt;
In Visual Prolog programs exceptions are used to deal with deviations from what is expected in the given context.  When a certain program part gets into a situation it cannot deal with it can &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;raise&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039; an exception.  When an exception is raised the program control is transferred to the nearest &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;exception handler&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;.  If the exception handler cannot handle the exception it can either raise a new exception or &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;continue&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039; the original exception.&lt;br /&gt;
&lt;br /&gt;
The program will terminate with an error message if there is no exception handler to transfer the control to.&lt;br /&gt;
&lt;br /&gt;
=== Introduction to exception handling  ===&lt;br /&gt;
&lt;br /&gt;
There are many concepts and entities to understand when dealing with exceptions.  This section will give an introduction by means of an example.&lt;br /&gt;
&lt;br /&gt;
A certain program needs to write some information to a file.  Therefore it has a predicate &amp;lt;vp&amp;gt;writeInfo&amp;lt;/vp&amp;gt; that can write this information.  &amp;lt;vp&amp;gt;writeInfo&amp;lt;/vp&amp;gt; calls the PFC constructor &amp;lt;vp&amp;gt;outputStream_file::create&amp;lt;/vp&amp;gt; to obtain a stream that it can write the information to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;clauses&lt;br /&gt;
    writeInfo(Filename) :-&lt;br /&gt;
        S = outputStream_file::create(Filename),&lt;br /&gt;
        …&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
But if the file already exists and is write-protected it is impossible to create the stream.&lt;br /&gt;
&lt;br /&gt;
In &amp;lt;vp&amp;gt;outputStream_file::create&amp;lt;/vp&amp;gt; this situation is considered to be exceptional/unexpected and therefore it raises an exception.&lt;br /&gt;
&lt;br /&gt;
When an exception is raised the program control is transferred to the nearest exception handler, which can hopefully handle the situation and thus bring the program back on track again.&lt;br /&gt;
&lt;br /&gt;
In this case &amp;lt;vp&amp;gt;writeInfo&amp;lt;/vp&amp;gt; is called after the user have entered the file name in a dialog and pressed a &amp;#039;&amp;#039;&amp;#039;Save&amp;#039;&amp;#039;&amp;#039;-button.  So the handling we want is simply to tell the user that the information was not written because the file was write-protected.  The user can choose a different filename, remove the write protection, delete the file, cancel the operation entirely or something else.  But from the program&amp;#039;s point of view the exceptional situation is handled.&lt;br /&gt;
&lt;br /&gt;
To set a handler we use the {{lang2|Terms|try-catch|try-catch}} language construction:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;clauses&lt;br /&gt;
    saveInfo(Filename) :-&lt;br /&gt;
        try&lt;br /&gt;
            writeInfo(Filename)&lt;br /&gt;
         catch TraceId do&lt;br /&gt;
              % &amp;lt;&amp;lt;handle situation&amp;gt;&amp;gt;&lt;br /&gt;
         end try.&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The code works like this:  &amp;lt;vp&amp;gt;writeInfo&amp;lt;/vp&amp;gt; is called, if it succeeds the {{lang2|Terms|try-catch|try-catch}} construction will not do more and &amp;lt;vp&amp;gt;saveInfo&amp;lt;/vp&amp;gt; will also succeed.&lt;br /&gt;
&lt;br /&gt;
But in the write-protected case &amp;lt;vp&amp;gt;outputStream_file::create&amp;lt;/vp&amp;gt; will raise an exception and therefore the following will take place:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;vp&amp;gt;TraceId&amp;lt;/vp&amp;gt; will be bound to the (so called) &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;trace id&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;, which is a handle to information about the exception (described in more details below)&lt;br /&gt;
# The handler code (i.e. the code between &amp;lt;vp&amp;gt;do&amp;lt;/vp&amp;gt; and &amp;lt;vp&amp;gt;end try&amp;lt;/vp&amp;gt;) is evaluated&lt;br /&gt;
# The result of the handler code will be the result of the {{lang2|Terms|try-catch|try-catch}} construction, and thus of &amp;lt;vp&amp;gt;saveInfo&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
So for the &amp;quot;write-protected&amp;quot; exception the handler code should write a message to the user.&lt;br /&gt;
&lt;br /&gt;
If it is another kind of exception the handler will have to do something different.  Especially, it may be an exception that the handler does not know how to handle.  In this case the best thing the handler code can do is to continue the exception as an &amp;#039;&amp;#039;unknown&amp;#039;&amp;#039; exception (i.e. unknown to the handler).&lt;br /&gt;
&lt;br /&gt;
When an exception is continued it consists of the original exception plus some continue information.  If it has been continued by several handlers it will contain a lot of continue information in addition to the original exception information.  The exception information describes a trace from the point of raise through all the handlers.  The &amp;lt;vp&amp;gt;TraceId&amp;lt;/vp&amp;gt; variable that is bound in the {{lang2|Terms|try-catch|try-catch}} construction gives access information about the entire trace (hence the name).&lt;br /&gt;
&lt;br /&gt;
As mentioned above the program will terminate with an error message, if an exception is raised and no handler can be found.  Therefore programs normally setup an outermost default exception handler.  &amp;lt;vp&amp;gt;mainExe::run&amp;lt;/vp&amp;gt; setup such a handler in a console program this is the fall-back handler.  In a GUI program there is also a default hander in the GUI event loop which will catch exceptions arising from the handling of an event.&lt;br /&gt;
&lt;br /&gt;
All in all, the lifecycle of an exception is as follows:&lt;br /&gt;
&lt;br /&gt;
* It is raised&lt;br /&gt;
* It is caught and continued&lt;br /&gt;
* It is caught and continued&lt;br /&gt;
* …&lt;br /&gt;
* It is caught and handled (or the program terminates with an error message)&lt;br /&gt;
&lt;br /&gt;
Each time the exception is caught the trace so far can be examined.  When the exception is raised and each time it is continued extra information can be added to the exception trace.  If nothing else handles an exception it will (normally) be handled by the fallback/default handler of the program.&lt;br /&gt;
&lt;br /&gt;
=== Defining an exception ===&lt;br /&gt;
&lt;br /&gt;
An exception is a value of the type &amp;lt;vp&amp;gt;core::exception&amp;lt;/vp&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;domains&lt;br /&gt;
    exception =  exception(string ClassName, string ExceptionName, string Description).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
I.e. an exception is a functor term that contains three pieces of information:&lt;br /&gt;
&lt;br /&gt;
; &amp;lt;vp&amp;gt;ClassName&amp;lt;/vp&amp;gt;&lt;br /&gt;
: The name of the class that defines the exception&lt;br /&gt;
; &amp;lt;vp&amp;gt;ExceptionName&amp;lt;/vp&amp;gt;&lt;br /&gt;
: Then name of the exception typically the name of a constant in the program&lt;br /&gt;
; &amp;lt;vp&amp;gt;Description&amp;lt;/vp&amp;gt;&lt;br /&gt;
: A description of the exception&lt;br /&gt;
&lt;br /&gt;
{{example| The &amp;lt;vp&amp;gt;cannotCreate&amp;lt;/vp&amp;gt; exception from the example above is declared in the class &amp;lt;vp&amp;gt;fileSystem_api&amp;lt;/vp&amp;gt; like this:&lt;br /&gt;
&amp;lt;vip&amp;gt;class fileSystem_api&lt;br /&gt;
…&lt;br /&gt;
constants&lt;br /&gt;
    cannotCreate : exception = exception(class_name(), constant_name(), &amp;quot;Cannot create or open the specified file&amp;quot;).&lt;br /&gt;
…&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Language_Reference/Built-in_entities/Predicates#class_name|&amp;lt;vp&amp;gt;class_name/0-&amp;gt;&amp;lt;/vp&amp;gt;]] and [[Language_Reference/Built-in_entities/Predicates#class_name|&amp;lt;vp&amp;gt;constant_name/0-&amp;gt;&amp;lt;/vp&amp;gt;]] are built-in predicate that returns the name if the class/constant in which the call occurs.  So the line above is equivalent to this:&lt;br /&gt;
&amp;lt;vip&amp;gt;class fileSystem_api&lt;br /&gt;
…&lt;br /&gt;
constants&lt;br /&gt;
    cannotCreate : exception = exception(&amp;quot;fileSystem_api&amp;quot;, &amp;quot;cannotCreate&amp;quot;, &amp;quot;Cannot create or open the specified file&amp;quot;).&lt;br /&gt;
…&amp;lt;/vip&amp;gt;&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Many/most programmers will never need to define exceptions, because in many/most cases the exceptions to use are already defined.  An exception definition is only needed when the exception must be distinguished from other kinds of exceptions, such that exception handlers can deal specially with that kind of exception.  Typically exception definitions are only necessary for exceptions that are raised by library software.  In most cases programmers will raise the exception &amp;lt;vp&amp;gt;internal_error&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Raising an exception ===&lt;br /&gt;
&lt;br /&gt;
There are many predicates that explicitly raises exceptions, but most of them does it by calling a predicate in &amp;lt;vp&amp;gt;exception&amp;lt;/vp&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;class exception&lt;br /&gt;
…&lt;br /&gt;
predicates&lt;br /&gt;
    raise_exception : (exception Exception, ...) erroneous [programPoint].&lt;br /&gt;
    raiseDetailes : (exception Exception, namedValue* ExtraInfo) erroneous [programPoint].&lt;br /&gt;
    raise_definiteUser : (exception Exception, string Msg, namedValue* ExtraInfo) erroneous [programPoint].&lt;br /&gt;
    ...&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In all cases the &amp;lt;vp&amp;gt;Exception&amp;lt;/vp&amp;gt; is the exception to raise and the rest of the arguments provides additional information about the exception.  See also [[Language Reference/Predicates#programPoint|programPoint in Language Reference]] for information about the programPoint attribute.&lt;br /&gt;
&lt;br /&gt;
{{example|The &amp;lt;vp&amp;gt;cannotCreate&amp;lt;/vp&amp;gt; exception from above is raised by the predicate &amp;lt;vp&amp;gt;fileSystem_api::raise_cannotCreate&amp;lt;/vp&amp;gt;/&amp;lt;vp&amp;gt;fileSystem_api::raise_cannotCreate_explicit&amp;lt;/vp&amp;gt;. The code  looks like this:&lt;br /&gt;
&amp;lt;vip&amp;gt;clauses&lt;br /&gt;
    raise_cannotCreate_explicit(ProgramPoint, FileName, LastError) :-&lt;br /&gt;
        Desc = getLastErrorDescription(LastError),&lt;br /&gt;
        Msg = string::format(&amp;quot;Cannot create or open &amp;#039;%%%s&amp;#039;\nError = 0x%08x\n%%%s&amp;quot;,&lt;br /&gt;
            fileSystem_fileName_parameter, LastError, errorDescription_parameter),&lt;br /&gt;
        raise_definiteUser_explicit(ProgramPoint, cannotCreate, Msg,&lt;br /&gt;
            [namedValue(fileSystem_fileName_parameter, string(FileName)),&lt;br /&gt;
            namedValue(fileSystem_path_parameter, string(directory::getCurrentDirectory())),&lt;br /&gt;
            namedValue(errorCode_parameter, unsigned(LastError)),&lt;br /&gt;
            namedValue(errorDescription_parameter, string(Desc))]).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vp&amp;gt;raise_cannotCreate_explicit&amp;lt;/vp&amp;gt; is called with the &amp;lt;vp&amp;gt;ProgramPoint&amp;lt;/vp&amp;gt; of the raising predicate, the &amp;lt;vp&amp;gt;FileName&amp;lt;/vp&amp;gt; and the windows error code &amp;lt;vp&amp;gt;LastError&amp;lt;/vp&amp;gt; that the relevant low level Windows API predicate caused.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vp&amp;gt;exception::getLastErrorDescription&amp;lt;/vp&amp;gt; obtains the description corresponding to &amp;lt;vp&amp;gt;LastError&amp;lt;/vp&amp;gt; from Windows.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vp&amp;gt;exception::raise_definiteUser_explict&amp;lt;/vp&amp;gt; is then used to raise the &amp;lt;vp&amp;gt;cannotCreate&amp;lt;/vp&amp;gt; exception with the four pieces of extra information.  The destinction between &amp;#039;&amp;#039;errors&amp;#039;&amp;#039;, &amp;#039;&amp;#039;user errors&amp;#039;&amp;#039; and &amp;#039;&amp;#039;definite user errors&amp;#039;&amp;#039; are described below.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
It is very common to create helper predicates like  &amp;lt;vp&amp;gt;fileSystem_api::raise_cannotCreate&amp;lt;/vp&amp;gt; to do the actual raising rather that calling one of the predicates in &amp;lt;vp&amp;gt;exception&amp;lt;/vp&amp;gt; directly from the code that needs to raise the exception.  That way it is certain that the extra info for this particular exception is handled in the same way in all cases.&lt;br /&gt;
&lt;br /&gt;
Normally, the helper raise predicate is created by the same programmer that declares the exception.  And as mentioned above this is normally only programmers that create library software.&lt;br /&gt;
&lt;br /&gt;
Application programmers will in most cases raise exceptions by calling appropriate raiser predicates, typically the some defined in &amp;lt;vp&amp;gt;exception&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Catching and handling exceptions ===&lt;br /&gt;
&lt;br /&gt;
Exceptions are caught with the {{lang2|Terms|try-catch|try-catch}} construction:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vipbnf&amp;gt;try &amp;lt;Body&amp;gt; catch &amp;lt;TraceId&amp;gt; do &amp;lt;Handler&amp;gt; end try&amp;lt;/vipbnf&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If &amp;lt;vpbnf&amp;gt;&amp;lt;Body&amp;gt;&amp;lt;/vpbnf&amp;gt; terminates with an exception &amp;lt;vpbnf&amp;gt;&amp;lt;TraceId&amp;gt;&amp;lt;/vpbnf&amp;gt; is bound to the &amp;#039;&amp;#039;trace id&amp;#039;&amp;#039; and then &amp;lt;vpbnf&amp;gt;&amp;lt;Handler&amp;gt;&amp;lt;/vpbnf&amp;gt; is evaluated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vpbnf&amp;gt;&amp;lt;TraceId&amp;gt;&amp;lt;/vpbnf&amp;gt; is used to obtain information about the exception trace.  This information can be used for at least two things:&lt;br /&gt;
&lt;br /&gt;
* Determine which kind of exception that is caught, so that it can be decided if and how to handle it&lt;br /&gt;
* Obtain additional information to write to the user, in a log or use for something else&lt;br /&gt;
&lt;br /&gt;
As explained above it is very common that an exception is continued one or more times after it has been raised, so an exception contains a complete &amp;#039;&amp;#039;trace&amp;#039;&amp;#039; of entries (raise, continue, continue, ---).  Subsequently, you will need to search the trace to see if a certain exception is among the entries.  This is done by calling &amp;lt;vp&amp;gt;exception::tryGetDescriptor&amp;lt;/vp&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;predicates&lt;br /&gt;
    tryGetDescriptor : (traceId TraceID, exception Exception) -&amp;gt; descriptor Descriptor determ.&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The exception trace corresponding to &amp;lt;vp&amp;gt;TraceId&amp;lt;/vp&amp;gt; is searched for an exception of the kind &amp;lt;vp&amp;gt;Exception&amp;lt;/vp&amp;gt;.  If there is such an entry in the trace (raised or continued) the corresponding exception descriptor is returned in &amp;lt;vp&amp;gt;Descriptor&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The predicate fails if such an exception is not in the exception trace.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;vp&amp;gt;Descriptor&amp;lt;/vp&amp;gt; contains the extra information about that particular entry in the exception trace:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;domains&lt;br /&gt;
    descriptor = descriptor(programPointDescriptor ProgramPoint, exception Exception, &lt;br /&gt;
        kind Kind, namedValue* ExtraInfo, gmtTimeValue GMTTime, unsigned ThreadId).&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vp&amp;gt;ProgramPoint&amp;lt;/vp&amp;gt;&lt;br /&gt;
: A readable representation of the &amp;lt;vp&amp;gt;programPoint&amp;lt;/vp&amp;gt; where the exception was raised/continued.&lt;br /&gt;
&amp;lt;vp&amp;gt;Exception&amp;lt;/vp&amp;gt;&lt;br /&gt;
: The &amp;lt;vp&amp;gt;exception&amp;lt;/vp&amp;gt; in question&lt;br /&gt;
&amp;lt;vp&amp;gt;Kind&amp;lt;/vp&amp;gt;&lt;br /&gt;
: The entry kind (&amp;lt;vp&amp;gt;raise&amp;lt;/vp&amp;gt; or &amp;lt;vp&amp;gt;continue&amp;lt;/vp&amp;gt;)&lt;br /&gt;
&amp;lt;vp&amp;gt;ExtraInfo&amp;lt;/vp&amp;gt;&lt;br /&gt;
: The extra information provided with this entry in the trace&lt;br /&gt;
&amp;lt;vp&amp;gt;GMTTime&amp;lt;/vp&amp;gt;&lt;br /&gt;
: The time this exception trace entry was raised/continued&lt;br /&gt;
&amp;lt;vp&amp;gt;ExceptionDescription&amp;lt;/vp&amp;gt;&lt;br /&gt;
: The exception description of this entry (this information is also present in &amp;lt;vp&amp;gt;ExceptionInfo&amp;lt;/vp&amp;gt;)&lt;br /&gt;
&amp;lt;vp&amp;gt;ThreadId&amp;lt;/vp&amp;gt;&lt;br /&gt;
: The thread id of the thread that raised/continued this entry&lt;br /&gt;
&lt;br /&gt;
Much of this information is mainly interesting if the exception is not handled.  The information that is most interesting when handling an exception is:&lt;br /&gt;
&lt;br /&gt;
* The exception has been determined to be the one we expected&lt;br /&gt;
* The &amp;lt;vp&amp;gt;ExtraInfo&amp;lt;/vp&amp;gt; for this entry is available for use in messages, etc&lt;br /&gt;
&lt;br /&gt;
The predicate &amp;lt;vp&amp;gt;exception::tryGetExtraInfo&amp;lt;/vp&amp;gt; is convenient for obtaining extra information:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;predicates&lt;br /&gt;
    tryGetExtraInfo : (descriptor Descriptor, string Name) -&amp;gt; value Value determ.&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vp&amp;gt;Descriptor&amp;lt;/vp&amp;gt;&lt;br /&gt;
: Is the description whose extra info we want to get something from.&lt;br /&gt;
&amp;lt;vp&amp;gt;Name&amp;lt;/vp&amp;gt;&lt;br /&gt;
: The name of the extra info parameter we want to obtain.&lt;br /&gt;
&amp;lt;vp&amp;gt;Value&amp;lt;/vp&amp;gt;&lt;br /&gt;
: The value that the mentioned parameter has.&lt;br /&gt;
&lt;br /&gt;
{{example| Code for catching and handling the &amp;lt;vp&amp;gt;fileSystem_api::cannotCreate&amp;lt;/vp&amp;gt; exception can look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;clauses&lt;br /&gt;
    saveInfo(Filename) :-&lt;br /&gt;
        try&lt;br /&gt;
            writeInfo(Filename)&lt;br /&gt;
         catch TraceId do&lt;br /&gt;
              if D = exception::tryGetDescriptor(TraceId, fileSystem_api::cannotCreate) then&lt;br /&gt;
                stdio::write(&amp;quot;Cannot write to the file: &amp;quot;, Filename),&lt;br /&gt;
                if string(Description) = exception::tryGetExtraInfo(D, exception::errorDescription_parameter) then&lt;br /&gt;
                    stdio::writef(&amp;quot;; %&amp;quot;, Description)&lt;br /&gt;
                end if,&lt;br /&gt;
                stdio::write(&amp;quot;\n&amp;quot;)&lt;br /&gt;
            else&lt;br /&gt;
                exception::continue_unknown(TraceId, &amp;quot;Filename = &amp;quot;, Filename)&lt;br /&gt;
            end if&lt;br /&gt;
         end try.&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The code here don&amp;#039;t need to obtain the &amp;lt;vp&amp;gt;fileSystem_exception::fileName_parameter&amp;lt;/vp&amp;gt;, because the file name is already known in the &amp;lt;vp&amp;gt;Filename&amp;lt;/vp&amp;gt; variable.&lt;br /&gt;
&lt;br /&gt;
But we can obtain Window&amp;#039;s description of the problem querying for &amp;lt;vp&amp;gt;common_exception::errorDescription_parameter&amp;lt;/vp&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We &amp;#039;&amp;#039;&amp;#039;continue&amp;#039;&amp;#039;&amp;#039; the exception as unknown if it is not a &amp;lt;vp&amp;gt;cannotCreate&amp;lt;/vp&amp;gt; exception.  For the continue call we add the filename as additional information.  &amp;lt;vp&amp;gt;common_exception::continue_unknown&amp;lt;/vp&amp;gt; will create a string of the extra arguments and add it as an &amp;lt;vp&amp;gt;common_exception::errorArguments_parameter&amp;lt;/vp&amp;gt;.  Such information is mainly for use in the default exception handler to be discussed below.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
=== Exception dumps ===&lt;br /&gt;
&lt;br /&gt;
The class &amp;lt;vp&amp;gt;exceptionDump&amp;lt;/vp&amp;gt; contains predicates for dumping exception traces to &amp;lt;vp&amp;gt;stdio&amp;lt;/vp&amp;gt;, some other &amp;lt;vp&amp;gt;outputStream&amp;lt;/vp&amp;gt; or a &amp;lt;vp&amp;gt;string&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
An exception dump contains three major pieces of information:&lt;br /&gt;
&lt;br /&gt;
* A dump of the call stack (with file names and line numbers) from the point where the exception was raised&lt;br /&gt;
* A dump of the exception-trace with all the information from the exception descriptors&lt;br /&gt;
* Information about the operating system that the program ran on&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vp&amp;gt;exceptionDump&amp;lt;/vp&amp;gt; have predicates both for dumping exception traces both from a &amp;lt;vp&amp;gt;traceId&amp;lt;/vp&amp;gt; and from a &amp;lt;vp&amp;gt;traceInfo&amp;lt;/vp&amp;gt; obtained with &amp;lt;vp&amp;gt;exception::getTraceInfo&amp;lt;/vp&amp;gt; (see [[#Serializing exceptions]] below).&lt;br /&gt;
&lt;br /&gt;
Dumps for a certain program are in general only useful to the programmers of that program; the users of the program will find dumps cryptic and rather uninteresting.  I.e. the purpose of dumps is to give the programmer means for improving the program.&lt;br /&gt;
&lt;br /&gt;
=== Default handling ===&lt;br /&gt;
&lt;br /&gt;
A program should handle all exceptions, because if an exception is continued or raised at a point where there is no handler the program will terminate with a rather bad error message.  The error message is bad because most exception handling is done in PFC; the language itself knows nothing about exception traces and the like.&lt;br /&gt;
&lt;br /&gt;
To be sure that all exceptions are handled it is normal to set up a default (or fallback) exception handler.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vp&amp;gt;mainExe::run&amp;lt;/vp&amp;gt; (and &amp;lt;vp&amp;gt;mainExe::runCom&amp;lt;/vp&amp;gt;) which is normally called in the goal setup such a default exception handler: It runs the &amp;lt;vp&amp;gt;main::run&amp;lt;/vp&amp;gt; predicate inside a {{lang2|Terms|try-catch|try-catch}} construction that will handle any exception.&lt;br /&gt;
&lt;br /&gt;
The handler in &amp;lt;vp&amp;gt;mainExe::run&amp;lt;/vp&amp;gt; (and &amp;lt;vp&amp;gt;mainExe::runCom&amp;lt;/vp&amp;gt;) dumps the entire exception trace to output stream in &amp;lt;vp&amp;gt;stdio&amp;lt;/vp&amp;gt;.  And then the program will terminate.  The idea is that:&lt;br /&gt;
&lt;br /&gt;
* Perhaps the user can see something from the dump (which may for example say that &amp;#039;&amp;#039;access is denied&amp;#039;&amp;#039; to &amp;#039;&amp;#039;xxx.txt&amp;#039;&amp;#039;)&lt;br /&gt;
* Alternatively, the developer of the program may use the dump to improve the program&lt;br /&gt;
&lt;br /&gt;
In addition to the handler in &amp;lt;vp&amp;gt;mainExe::run&amp;lt;/vp&amp;gt; a GUI program also set a default handler in the event loop.  This handler is set by calling &amp;lt;vp&amp;gt;applicationWindow::setErrorResponder&amp;lt;/vp&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;domains&lt;br /&gt;
    errorResponder = (applicationWindow Source, exception::traceId TraceId).&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    setErrorResponder : (errorResponder Responder).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
By default the error responder &amp;lt;vp&amp;gt;errorPresentationDialog::present&amp;lt;/vp&amp;gt; is used.  The functioning of the &amp;lt;pv&amp;gt;errorPresentationDialog&amp;lt;/vp&amp;gt; is closely related to a categorization of exceptions described in the next section.&lt;br /&gt;
&lt;br /&gt;
PFC place exceptions in three major categories based on who is (believed to be) responsible:&lt;br /&gt;
&lt;br /&gt;
; Internal errors&lt;br /&gt;
: An exceptional state which the programmer is responsible to deal with&lt;br /&gt;
; User exception&lt;br /&gt;
: An exception which can perhaps be solved by the end user of the program, but which may also call for a programmer solution.  User exceptions carries a message for the end user of the program.&lt;br /&gt;
; Definite user errors&lt;br /&gt;
: An exception which is definitely one the end user should deal with, because the programmer cannot do anything about it anyway&lt;br /&gt;
&lt;br /&gt;
You may notice that &amp;quot;error&amp;quot; is used to signal that a person is (believed to be) responsible for the problem, where as &amp;quot;exception&amp;quot; also covers situations with looser relation to specific persons (such as a network failure).&lt;br /&gt;
&lt;br /&gt;
==== Internal errors ====&lt;br /&gt;
&lt;br /&gt;
Internal errors are caused and/or should be prevented by the programmer of the program.&lt;br /&gt;
&lt;br /&gt;
{{Example| A predicate takes two lists as argument and pair the elements of the lists.  So the lists are expected to have the same length.  If the lists have different lengths it is appropriate to raise an &amp;lt;vp&amp;gt;internal_error&amp;lt;/vp&amp;gt;, because it is clearly the responsibility of the programmer to ensure that the lists have same length; the end-user of the program can at most influence this indirectly.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== User exceptions ====&lt;br /&gt;
&lt;br /&gt;
User exceptions typically deal with problems related to external resources such as files, network, databases, web servers, etc.  Often the user will become wiser by being informed about the problem and often the user may even solve the problem.&lt;br /&gt;
&lt;br /&gt;
{{Example|  The read-only file problem discussed above is a typical example of a user exception.  It is the user rather than the programmer that can solve the problem with the read-only file.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A user exception is distinguished by having extra information in a field with name &amp;lt;vp&amp;gt;common_exception::userMessage_parameter&amp;lt;/vp&amp;gt;.  This extra info should be a message with relevance for an end user of the program.  The message can reference other extra info parameters using the format %PARAM.  The preferred way to raise user exceptions is by means of the predicate &amp;lt;vp&amp;gt;exception::raise_user&amp;lt;/vp&amp;gt;.  Likewise you can continue exceptions with a user message using &amp;lt;vp&amp;gt;exception::continue_user&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
{{Example| This predicate will raise a &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;user&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039; &amp;lt;vp&amp;gt;fileSystem_api::cannotCreate&amp;lt;/vp&amp;gt; exception&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;class predicates&lt;br /&gt;
    raise_cannotCreate : (string Filename) erroneous.&lt;br /&gt;
clauses&lt;br /&gt;
    raise_cannotCreate(Filename) :-&lt;br /&gt;
        exception::raise_user(fileSystem_api::cannotCreate,&lt;br /&gt;
            &amp;quot;It is not possible to create the file %Filename&amp;quot;,&lt;br /&gt;
            [namedValue(&amp;quot;Filename&amp;quot;, string(Filename))]).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The use of &amp;lt;vp&amp;gt;&amp;quot;%Filename&amp;quot;&amp;lt;/vp&amp;gt; in the message corresponds to the extra info &amp;lt;vp&amp;gt;&amp;quot;Filename&amp;quot;&amp;lt;/vp&amp;gt;.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The predicate &amp;lt;vp&amp;gt;exceptionDump::tryGetUserMessage&amp;lt;/vp&amp;gt; will return a user message from a &amp;lt;vp&amp;gt;traceId&amp;lt;/vp&amp;gt; if possible.  The message will consist of all user messages from the entire trace and will have parameters substituted.&lt;br /&gt;
&lt;br /&gt;
{{Example|  Given &amp;lt;vp&amp;gt;raise_cannotCreate&amp;lt;/vp&amp;gt; from above and calling &amp;lt;vp&amp;gt;test&amp;lt;/vp&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;clauses&lt;br /&gt;
    test() :-&lt;br /&gt;
        try&lt;br /&gt;
            raise_cannotCreate(&amp;quot;test.xxx&amp;quot;)&lt;br /&gt;
         catch TraceId do&lt;br /&gt;
            if UserMsg = exceptionDump::tryGetUserMessage(TraceId) then&lt;br /&gt;
                stdio::write(UserMsg)&lt;br /&gt;
            end if&lt;br /&gt;
         end try.&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following message is written to &amp;lt;vp&amp;gt;stdio&amp;lt;/vp&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;It is not possible to create the file test.xxx&amp;lt;/source&amp;gt;&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== Definite user errors ====&lt;br /&gt;
&lt;br /&gt;
Definite user errors are exceptions that are solely the responsibility of the user of the program.  For example wrong use of the program.&lt;br /&gt;
&lt;br /&gt;
{{Example| A program can write out some information, but only if the user has specified which information to write.  So if the user invoke the functionality without having specified which information to write, it is appropriate to raise a definite user error.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A definite user exception is distinguished by adding &amp;lt;vp&amp;gt;true&amp;lt;/vp&amp;gt; as extra info for the parameter &amp;lt;vp&amp;gt;exception::definiteUserError_parameter&amp;lt;/vp&amp;gt;.  The preferred way to do this is by using the predicates:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;vp&amp;gt;exception::raise_definiteUser&amp;lt;/vp&amp;gt;&lt;br /&gt;
* &amp;lt;vp&amp;gt;exception::continue_definiteUser&amp;lt;/vp&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The use of these predicates is the same as the user of &amp;lt;vp&amp;gt;common_exception::raise_user&amp;lt;/vp&amp;gt; and &amp;lt;vp&amp;gt;common_exception::continue_user&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
An exception trace is considered a definite user error if one (or more) entries in the trace carries the &amp;lt;vp&amp;gt;exception::definiteUserError_parameter&amp;lt;/vp&amp;gt;.  The predicate &amp;lt;vp&amp;gt;exception::isDefiniteUserError&amp;lt;/vp&amp;gt; will succeed for definite user errors.&lt;br /&gt;
&lt;br /&gt;
=== Serializing exceptions ===&lt;br /&gt;
&lt;br /&gt;
In some situations the best way to handle  an exception is by sending all the information about the exception somewhere else.  A server might for example want to send the information to the client program that caused the exception, because then there is a user that can take action.&lt;br /&gt;
&lt;br /&gt;
A &amp;lt;vp&amp;gt;traceId&amp;lt;/vp&amp;gt; only have a meaning in the process that has created it, but the predicate &amp;lt;vp&amp;gt;exception::getTraceInfo&amp;lt;/vp&amp;gt; can create a &amp;lt;vp&amp;gt;traceInfo&amp;lt;/vp&amp;gt; structure (&amp;lt;vp&amp;gt;TraceInfo&amp;lt;/vp&amp;gt;) from the &amp;lt;vp&amp;gt;traceId TraceId&amp;lt;/vp&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;predicates&lt;br /&gt;
    getTraceInfo : (traceId TraceId) -&amp;gt; traceInfo TraceInfo.&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Such a structure is a functor structure that can be serialized/deserialized with &amp;lt;vp&amp;gt;toString&amp;lt;/vp&amp;gt;/&amp;lt;vp&amp;gt;toTerm&amp;lt;/vp&amp;gt;; &amp;lt;vp&amp;gt;write&amp;lt;/vp&amp;gt;/&amp;lt;vp&amp;gt;read&amp;lt;/vp&amp;gt;; nested in a fact database using &amp;lt;vp&amp;gt;save&amp;lt;/vp&amp;gt;/&amp;lt;vp&amp;gt;consult&amp;lt;/vp&amp;gt;; etc.&lt;br /&gt;
&lt;br /&gt;
==== Packed Exceptions ====&lt;br /&gt;
&lt;br /&gt;
Sometimes, e.g., in a client/server application, you catch an exception on the server which you want to handle on the client. In that case you can serialize the exception on the server send it to the client and reraise it as a packed exception.&lt;br /&gt;
&lt;br /&gt;
On the server&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
try&lt;br /&gt;
   ...&lt;br /&gt;
catch E do&lt;br /&gt;
   sendExceptionToClient(exception::getTraceInfo())&lt;br /&gt;
end try,&lt;br /&gt;
...&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
On the client&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
...&lt;br /&gt;
Rtn = remoteCall(...),&lt;br /&gt;
if error(TraceInfo) = Rtn then&lt;br /&gt;
    exception::raise_packed(TraceInfo, &amp;quot;remoteCall returned an exception&amp;quot;)&lt;br /&gt;
end if&lt;br /&gt;
...&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The predicate &amp;lt;vp&amp;gt;raise_packed&amp;lt;/vp&amp;gt; works like a &amp;lt;vp&amp;gt;continue_unknown&amp;lt;/vp&amp;gt; but continues a serialized exception instead of normal exception. It is meant to be used when the exception stem from another program and thus only is available in serialized form.&lt;br /&gt;
&lt;br /&gt;
=== The error presentation dialog  ===&lt;br /&gt;
&lt;br /&gt;
The error presentation dialog (in the class &amp;lt;vp&amp;gt;errorPresentationDialog&amp;lt;/vp&amp;gt;) is by default used by the default exception handling in a GUI program.  Its behavior is closely related to the classification of exceptions described above, as described by these two rules:&lt;br /&gt;
&lt;br /&gt;
* If the exception trace carries a user message, this message will be presented to the user.&lt;br /&gt;
* If the exception trace is not a definite user error, there will be information for the programmer&lt;br /&gt;
&lt;br /&gt;
So if the exception is an internal error there will only be information for the programmer; if it is a user exception there will both be information for the user and for the programmer; and if it is a user error there will only be information for the user.&lt;br /&gt;
&lt;br /&gt;
If there is information to the programmer the exception dialog will have a details/less details button that can show/hide the programmer information.  It will also have a &amp;quot;report error&amp;quot; button, which by default will copy the information to the clipboard so that the user can easily send it to the programmer.&lt;br /&gt;
&lt;br /&gt;
[[Image:ErrorPresentationDialogDefault.png]]&lt;br /&gt;
&lt;br /&gt;
The dialog is customizable by means of various properties:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;properties&lt;br /&gt;
    title : string. % := &amp;quot;Error&amp;quot;.&lt;br /&gt;
    callBackBtnText : string. % := &amp;quot;&amp;amp;Copy&amp;quot;.&lt;br /&gt;
    dontCallBackBtnText : string. % := &amp;quot;&amp;amp;OK&amp;quot;.&lt;br /&gt;
    showDetailsBtnText : string. % := &amp;quot;Show &amp;amp;Details&amp;quot;.&lt;br /&gt;
    hideDetailsBtnText : string. % := &amp;quot;Hide &amp;amp;Details&amp;quot;.&lt;br /&gt;
    closeApplicationBtnText : string. % := &amp;quot;Close &amp;amp;Application&amp;quot;.&lt;br /&gt;
    commentTextPromt : string. % := &amp;quot;Please describe what you were doing when the error occured:&amp;quot;&lt;br /&gt;
    internalErrorMessage : string. %  := &amp;quot;An internal error has occurred.\nPlease send a bug report to your vendor.&amp;quot;.&lt;br /&gt;
    feedbackMessage : string. %  := &amp;quot;Please send your feedback.&amp;quot;.&lt;br /&gt;
    definiteUserErrorIcon : vpiDomains::resid.&lt;br /&gt;
    userErrorIcon : vpiDomains::resid.&lt;br /&gt;
    internalErrorIcon : vpiDomains::resid.&lt;br /&gt;
    reportErrorDelegate : reportErrorDelegate.&lt;br /&gt;
    extraInfoWriter : writer.&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
All texts and labels are controlled by properties.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;vp&amp;gt;extraInfoWriter&amp;lt;/vp&amp;gt; is a callback that can be set to include extra info for the programmer.  This information will both be presented in the details window and reported back to the programmer if the user press the &amp;quot;report error&amp;quot; button (i.e. the button which is by default labeled &amp;#039;&amp;#039;&amp;#039;Copy&amp;#039;&amp;#039;&amp;#039;).&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;vp&amp;gt;extraInfoWriter&amp;lt;/vp&amp;gt; callback predicate must have this type:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;domains&lt;br /&gt;
    writer = (outputStream Stream).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The dialog will invoke the predicate and then it should simply write extra information to the received stream.&lt;br /&gt;
&lt;br /&gt;
{{Example| The Visual Prolog IDE uses the &amp;lt;vp&amp;gt;extraInfoWriter&amp;lt;/vp&amp;gt; to write version information, information about the open project and information about the last actions carried out in the IDE.  This information will help the programmers to analyze the problem.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The action performed by the &amp;quot;report error&amp;quot; button is customizable using the property &amp;lt;vp&amp;gt;reportErrorDelegate&amp;lt;/vp&amp;gt;, which is a callback predicate of this type:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;domains&lt;br /&gt;
    reportErrorDelegate = (window Parent, string Comment, optional{exception::traceInfo} TraceInfo, string ExtraInfo).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
; &amp;lt;vp&amp;gt;Parent&amp;lt;/vp&amp;gt;&lt;br /&gt;
: The error presentation dialog which can be used as parent for additional dialogs.&lt;br /&gt;
; &amp;lt;vp&amp;gt;Comment&amp;lt;/vp&amp;gt;&lt;br /&gt;
: The users comment from the comment box.&lt;br /&gt;
; &amp;lt;vp&amp;gt;TraceInfo&amp;lt;/vp&amp;gt;&lt;br /&gt;
: If the dialog is invoked on an exception the trace info is here, if it is invoked for feedback this value is &amp;lt;vp&amp;gt;none&amp;lt;/vp&amp;gt;&lt;br /&gt;
; &amp;lt;vp&amp;gt;ExtraInfo&amp;lt;/vp&amp;gt;&lt;br /&gt;
: The extra info written by the &amp;lt;vp&amp;gt;extraInfoWriter&amp;lt;/vp&amp;gt; callback&lt;br /&gt;
&lt;br /&gt;
{{Example| In the Visual Prolog IDE the &amp;lt;vp&amp;gt;reportErrorDelegate&amp;lt;/vp&amp;gt; will send the exception information to a WEB service which will insert the notification in a database.  The notifications in the database will then be used to improve the IDE.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
[[Category:Tutorials]]&lt;/div&gt;</summary>
		<author><name>Kasper B H Petersen</name></author>
	</entry>
	<entry>
		<id>https://wiki.visual-prolog.com/index.php?title=Language_Reference/Objects_and_Polymorphism&amp;diff=4836</id>
		<title>Language Reference/Objects and Polymorphism</title>
		<link rel="alternate" type="text/html" href="https://wiki.visual-prolog.com/index.php?title=Language_Reference/Objects_and_Polymorphism&amp;diff=4836"/>
		<updated>2021-10-12T09:57:39Z</updated>

		<summary type="html">&lt;p&gt;Kasper B H Petersen: /* Subsumption polymorphism */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{languageReferenceNavbar|Generic Interfaces and Classes}}&lt;br /&gt;
&lt;br /&gt;
The programming language Visual Prolog has gone through a huge development in the latest years, and this will also continue in future. Most noticeable is the shift to object-orientation, and the introduction of parametric polymorphism. In this paper we will explain the reason for introducing these features. Examples will be used to illustrate how these facilities can help to tackle the increasing complexity and size of software.&lt;br /&gt;
&lt;br /&gt;
=== Motivation ===&lt;br /&gt;
&lt;br /&gt;
While Prolog has many great virtues, one must remember that it is from the IT-bronze-age, and it would be silly to think that it would stay contemporary after three decades or more, especially considering the speed with, which the IT-world has evolved since then. Back then you could write an amazing Prolog program that described how to get a cabbage, a goat, a wolf and a farmer across a river in a little boat without anybody eating anybody. You can still write such programs just as easily (see [[Farmer, Wolf, Goat and Cabbage]]), but they are just not that amazing anymore. Show it to your children and they will immediately ask why the solution is not an animation, and explain that there are millions of much more advanced programs one click away on the Internet already.&lt;br /&gt;
&lt;br /&gt;
Programs today must be more advanced than yesterday.  They also have to live and interact with a much larger world than yesterday.  And this is an ongoing story.&lt;br /&gt;
&lt;br /&gt;
Many attempts has been made to help tackle these challenges; we have chosen to add the elements that we believe are the winners to Visual Prolog. These are especially object-orientation and parametric polymorphism, but there are also other new elements especially taken from the functional programming world.&lt;br /&gt;
&lt;br /&gt;
=== Goals and Means ===&lt;br /&gt;
&lt;br /&gt;
The goals of the language update is to provide better means for creating and maintaining more complex programs for more complex surroundings.&lt;br /&gt;
&lt;br /&gt;
==== Simplicity ====&lt;br /&gt;
&lt;br /&gt;
Humans are better to dealing with simple things than complex things, so one important way to deal with complexity is to reduce it to something simpler, especially by using &amp;quot;structure&amp;quot; to organize the complexity.&lt;br /&gt;
&lt;br /&gt;
The main &amp;quot;trick&amp;quot; is the &amp;#039;&amp;#039;divide and conquer &amp;#039;&amp;#039; principle: Divide the original problem into separate sub-problems that can be solved individually. I.e., the solution to the overall problem consists of a number of sub-solutions and something that combines these into the overall solution.&lt;br /&gt;
&lt;br /&gt;
==== Maintainability ====&lt;br /&gt;
&lt;br /&gt;
For software it is often not enough to solve a problem, we must also be able to maintain and extend the solution in an evolving world.  So it is important that the used methods not only solve the problem, but also result in a program that can be maintained. Here it is important that the program is understandable and especially that the &amp;#039;&amp;#039;divides&amp;#039;&amp;#039; are visible and clear in the program.&lt;br /&gt;
&lt;br /&gt;
==== Reuse and sharing ====&lt;br /&gt;
&lt;br /&gt;
When you divide problems into sub-problems, perhaps repeatedly, you will sometimes see similar sub-problems. Then it would of course be nice to short cut by reusing a similar solution. Such a solution can be adopted into the new context, but there are two ways this can happen. We can make a copy and update it to its new purpose, or we can try to share the code between the two problems.&lt;br /&gt;
&lt;br /&gt;
The latter is clearly the hardest and only makes sense if both pieces of software are still maintained. But in that case you will have the advantage that maintenance made in one context is also shared with the other context.&lt;br /&gt;
&lt;br /&gt;
==== Flexibility ====&lt;br /&gt;
&lt;br /&gt;
It is also desirable that your software is flexible. You may for example need to deliver several variants of your software to different customers. Or you may need to reconfigure the software to a changed context.  Also some of your shared sub-solutions may need to go into contexts that are not completely the same.&lt;br /&gt;
&lt;br /&gt;
==== Power ====&lt;br /&gt;
&lt;br /&gt;
Finally, it is of course desirable if language extensions add additional programming power. For example, by simplifying the code necessary to tackle certain standard &amp;quot;issues&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=== Polymorphism ===&lt;br /&gt;
&lt;br /&gt;
Visual Prolog has been extended with many language features that support the goals above, but it is still up to the programmer to apply these features such that the goals are achieved. Here we will focus on understanding and using polymorphism.&lt;br /&gt;
&lt;br /&gt;
The object-system in Visual Prolog gives so called &amp;#039;&amp;#039;subsumption polymorphism&amp;#039;&amp;#039; and also have &amp;#039;&amp;#039;parametric polymorphism&amp;#039;&amp;#039;. Polymorphism is especially well-suited for &amp;#039;&amp;#039;divide and conquer&amp;#039;&amp;#039; that supports &amp;#039;&amp;#039;sharing&amp;#039;&amp;#039; of code.&lt;br /&gt;
&lt;br /&gt;
==== Subsumption polymorphism ====&lt;br /&gt;
&lt;br /&gt;
An object is a closed entity that carries state and code. The object provides an interface through which the surroundings can interact with the object. The object can also interact with other objects through their interfaces.&lt;br /&gt;
&lt;br /&gt;
Each interface has an explicit definition in the source code. The definition effectively consists of a name and a number of predicate declarations.&lt;br /&gt;
&lt;br /&gt;
Let us assume that we want an object through which some administrative system can report salary. In an oversimplified world, such an object might have this interface:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
interface salarySystem&lt;br /&gt;
predicates&lt;br /&gt;
    salary : (string Name,  real Amount).&lt;br /&gt;
end interface salarySystem&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An object with this interface will allow you to report an &amp;lt;vp&amp;gt;Amount&amp;lt;/vp&amp;gt; for a person (identified by &amp;lt;vp&amp;gt;Name&amp;lt;/vp&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
The  salarySystem interface defines a data type that can be used in the program. The main salary reporting predicate in the application might be declared like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
class predicates&lt;br /&gt;
    reportSalary : (salarySystem SalarySystem).&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the sake of the example, we simply hard code a little salary reporting like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
clauses&lt;br /&gt;
    reportSalary(SalarySystem) :-&lt;br /&gt;
        SalarySystem:salary(&amp;quot;John D&amp;quot;, 135.12),&lt;br /&gt;
        SalarySystem:salary(&amp;quot;Elvis P&amp;quot;, 117.00).&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will of course also need to implement our salary system objects, and that is where the subsumption polymorphism comes in play.  The thing is that our customers of course use a lot of different salary systems, which must receive input in many different formats and using many different media. Objects are implemented by classes, and the fortunate thing is that many different classes can implement the same interface. Objects produced by any such class can be used by the reportSalary predicate.  Thus, the reportSalary predicate is &amp;#039;&amp;#039;polymorphic&amp;#039;&amp;#039; because the &amp;lt;vp&amp;gt;salarySystem&amp;lt;/vp&amp;gt; type &amp;#039;&amp;#039; subsumes&amp;#039;&amp;#039; all the different implementations of the interface. To deal with the ACME salary system we declare this class:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
class acme : salarySystem&lt;br /&gt;
end class acme&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The declaration simply says that &amp;lt;vp&amp;gt;acme&amp;lt;/vp&amp;gt; is a class that produces objects of type salarySystem. The class also needs an implementation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
implement acme&lt;br /&gt;
constants&lt;br /&gt;
    fmt = &amp;quot;SAL:%&amp;gt;&amp;gt;&amp;gt;%\n&amp;quot;.&lt;br /&gt;
clauses&lt;br /&gt;
    salary(Name, Amount) :-&lt;br /&gt;
        stdio::writef(fmt, Name, Amount).&lt;br /&gt;
end implement  acme&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To illustrate the polymorphism, we will also implement the integration to the O&amp;#039;Salery system. Again we declare and implement a class:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
class oSalary : salarySystem&lt;br /&gt;
end class oSalary&lt;br /&gt;
&lt;br /&gt;
implement oSalary&lt;br /&gt;
constants&lt;br /&gt;
    fmt = &amp;quot;&amp;lt;salary name=\&amp;quot;%\&amp;quot; wage=\&amp;quot;%\&amp;quot; /&amp;gt;\n&amp;quot;.&lt;br /&gt;
clauses&lt;br /&gt;
    salary(Name, Amount) :-&lt;br /&gt;
        stdio::writef(fmt, Name, Amount).&lt;br /&gt;
end implement oSalary&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now let us try our two salary system integrations:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
clauses&lt;br /&gt;
    test():-&lt;br /&gt;
        ACME = acme::new(),&lt;br /&gt;
        reportSalary(ACME),&lt;br /&gt;
        Osalery = oSalary::new(),&lt;br /&gt;
        reportSalary(Osalery).&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the test predicate above, we create one of each salary systems and report salary to them. The result looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
SAL:John D&amp;gt;&amp;gt;&amp;gt;135.12&lt;br /&gt;
SAL:Elvis P&amp;gt;&amp;gt;&amp;gt;117&lt;br /&gt;
&amp;lt;salary name=&amp;quot;John D&amp;quot; wage=&amp;quot;135.12&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;salary name=&amp;quot;Elvis P&amp;quot; wage=&amp;quot;117&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example, the difference was not that big, but we might also have placed the result in a database, used a foreign API, called a WEB service or whatever.&lt;br /&gt;
&lt;br /&gt;
The solution above uses the divide and conquer principle to separate the reporting in a vendor independent part and a vendor specific part. In this case the vendor independent part also deals with the company level in the reporting, were as the vendor dependent part only deals with the person level.&lt;br /&gt;
&lt;br /&gt;
We have used subsumption polymorphism to provide the flexibility to deal with many different salary systems in a seamless way. In real world, this may not be as simple as here though. The key to success is that the salarySystem interface is a sufficiently powerful abstraction/generalization of &amp;#039;&amp;#039;all&amp;#039;&amp;#039; the relevant salary systems. It may for example be necessary to provide several different ways to identify persons in the salary predicate.  Different salary systems can then use the identification method, which is appropriate for them and ignore the rest.&lt;br /&gt;
&lt;br /&gt;
The  reportSalary predicate is &amp;#039;&amp;#039;shared&amp;#039;&amp;#039; across different salary systems.  The sharing is a high-level domain specific sharing, within the same application or variants of it.&lt;br /&gt;
&lt;br /&gt;
Visual Prolog also has another kind of subsumption polymorphism: Predicate values. A predicate value is a predicate that is bound to variables, transferred as parameter and/or stored in facts. Again, the polymorphism comes from a type that &amp;#039;&amp;#039;subsumes&amp;#039;&amp;#039; many different implementations.&lt;br /&gt;
&lt;br /&gt;
As an example, PFC uses predicate values in its heavily used &amp;#039;&amp;#039;event notification scheme&amp;#039;&amp;#039;. A scheme that can of course also be used outside PFC.&lt;br /&gt;
&lt;br /&gt;
The event notification scheme has two kinds of actors: the event source and the event listener. There is one event source, but there can be any number of listeners. The event source offers predicates for registering and deregistering event listeners. When the event occurs all registered listeners are notified.&lt;br /&gt;
&lt;br /&gt;
The interesting thing is that the event listener is a predicate, meaning that the notification will immediately execute code. In addition, due to the subsumption polymorphism each listener can have its own implementation and thus perform quite different actions.&lt;br /&gt;
&lt;br /&gt;
A very important property of predicate values is that they can be &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;object&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039; predicates, and that these have access to the object state to which they belong.&lt;br /&gt;
&lt;br /&gt;
We shall not describe the event notification scheme in details here, though it is good to understand. The reader is encouraged to study the concept in PFC (look for &amp;#039;&amp;#039;addXxxxListener&amp;#039;&amp;#039;). However, the use of predicate values will be exercised in the job-scheduling example in the end of this paper.&lt;br /&gt;
&lt;br /&gt;
==== Parametric Polymorphism ====&lt;br /&gt;
&lt;br /&gt;
Like for subsumption polymorphism the purpose of &amp;#039;&amp;#039;parametric&amp;#039;&amp;#039; polymorphism is to use the same code for many things. However, where subsumption polymorphism is mainly about supplying different implementations to the same context, parametric polymorphism is mainly about using the same implementation in different contexts.&lt;br /&gt;
&lt;br /&gt;
Let us start with a very simple example, to introduce the concepts. We will implement a function, which takes the list as argument and returns the elements one by one (non-deterministically).&lt;br /&gt;
&lt;br /&gt;
In Visual Prolog the list domain is a polymorphic domain: If  Elem is a type/domain then Elem* the list domain of Elem.  The new thing is that &amp;#039;&amp;#039;parameters&amp;#039;&amp;#039; like Elem and type expressions like Elem* can be used in declarations, and that the resulting declaration will cover any instantiation of such parameters.&lt;br /&gt;
&lt;br /&gt;
Therefore we can declare our getMember_nd function like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
predicates&lt;br /&gt;
    getMember_nd : (Elem* List) -&amp;gt; Elem Value&lt;br /&gt;
        nondeterm.&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This declaration says that &amp;lt;vp&amp;gt;getMember_nd&amp;lt;/vp&amp;gt; is a function, which takes a list of Elem argument and returns an Elem, where Elem is any domain/type.&lt;br /&gt;
&lt;br /&gt;
The implementation is straightforward:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
clauses&lt;br /&gt;
    getMember_nd([V|_L]) = V.&lt;br /&gt;
    getMember_nd([_V|L]) = getMember_nd(L).&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Without further notice &amp;lt;vp&amp;gt;getMember_nd&amp;lt;/vp&amp;gt; can be used on any list kind:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
clauses&lt;br /&gt;
    run():-&lt;br /&gt;
        console::init(),&lt;br /&gt;
        L = [[1,2,3], [7,-7], [9,4,5]],&lt;br /&gt;
        foreach X = list::getMember_nd(L) do&lt;br /&gt;
            stdio::writef(&amp;quot;X = %\n&amp;quot;, X)&lt;br /&gt;
        end foreach.&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here &amp;lt;vp&amp;gt;Elem&amp;lt;/vp&amp;gt; is &amp;lt;vp&amp;gt;integer*&amp;lt;/vp&amp;gt; (i.e. list of integers). The output looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
X = [1,2,3]&lt;br /&gt;
X = [7,-7]&lt;br /&gt;
X = [9,4,5]&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The list domain is a predefined polymorphic domain. But you can also define polymorphic domains yourself. As an example we can create a &amp;#039;&amp;#039;priority queue&amp;#039;&amp;#039;; sometimes called a heap. Let me warn you, the implementation I will use here is not particularly efficient; it is just simple.&lt;br /&gt;
&lt;br /&gt;
The idea of the priority queue is that we can insert some data with a priority, later we can then retrieve the data with lowest priority.  It sounds a bit strange, that it is the one with the lowest Priority that is retrieved; but that is how it normally works. I assume that it comes from the idea of first priority, second priority, etc. where smaller number means higher priority.&lt;br /&gt;
&lt;br /&gt;
Anyway, in this case we want to implement the queue as a list of tuple&amp;#039;s, each tuple has two elements the first is the priority and the second is the Data.  Furthermore, we will keep the list sorted after priority (i.e. an invariant), such that the smallest element is always first in the list.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;tuple&amp;#039;&amp;#039;&amp;#039; is already defined in Visual Prolog its definition looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
domains&lt;br /&gt;
    tuple{T1, T2} = tuple(T1, T2).&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There are also tuple&amp;#039;s with other arities, but we only need the pair. This is an example of a programmer defined polymorphic domain. What the definition says is that tuple is a domain with two type parameters &amp;lt;vp&amp;gt;T1&amp;lt;/vp&amp;gt; and &amp;lt;vp&amp;gt;T2&amp;lt;/vp&amp;gt;.  You may think of it as an infinite family of domains corresponding to all instantiations of the type parameters, e.g.:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
domains&lt;br /&gt;
    tuple_char_char = tuple(char, char).&lt;br /&gt;
    tuple_char_integer = tuple(char, integer).&lt;br /&gt;
    tuple_char_string = tuple(char, string).&lt;br /&gt;
    ...&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The single domain definition above corresponds to all these domains, but actually the domain names/expressions look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
    tuple{char, char}&lt;br /&gt;
    tuple{char, integer}&lt;br /&gt;
    tuple{char, string}&lt;br /&gt;
    ...&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The values looks as expected; let us take a relatively complex one right away:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
    X = tuple(tuple(&amp;#039;a&amp;#039;,&amp;quot;a&amp;quot;), [1.2])&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
T2 is a tuple, its first element is itself a tuple (containing a char and a string), its second element is a list of  real&amp;#039;s. Subsequently, X has this type:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
    tuple{ tuple{char, string}, real* } &lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As you can see type expressions can become rather complex. You will probably soon get use to this, but below I will show a little scheme that can be used to keep type expressions simpler and more understandable, and which will at the same time make your program more type safe.&lt;br /&gt;
&lt;br /&gt;
We are now ready to define our queue domain:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
domains&lt;br /&gt;
    queue_rep{Priority, Data} = tuple{Priority, Data}*.&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;vp&amp;gt;_rep&amp;lt;/vp&amp;gt; in the domain name has to do with the scheme mentioned above, right now you can simply ignore it. The domain definition says that &amp;lt;vp&amp;gt;queue_rep&amp;lt;/vp&amp;gt; is a domain with two type parameters &amp;lt;vp&amp;gt;Priority&amp;lt;/vp&amp;gt; and &amp;lt;vp&amp;gt;Data&amp;lt;/vp&amp;gt; furthermore it is a list of tuple&amp;#039;s of these types.&lt;br /&gt;
&lt;br /&gt;
You may wonder why &amp;lt;vp&amp;gt;Priority&amp;lt;/vp&amp;gt; is a type parameter, you may think that it should have been a number type like integer. However, in Visual Prolog all data types are ordered, and therefore any data type can be used as a priority. Using a type parameter here makes the resulting queue more flexible. And at least I do not have to choose whether the priority should be integer, unsigned or real.&lt;br /&gt;
&lt;br /&gt;
To know whether you can use a type parameter or have to use a regular type you will have to consider what you need from the type. Like here where we need ordering (comparison). The following is possible on type parameters:&lt;br /&gt;
&lt;br /&gt;
*transferring as parameter&lt;br /&gt;
*binding and unifying (with values of same type)&lt;br /&gt;
*comparing (with values of same type)&lt;br /&gt;
*writing on streams&lt;br /&gt;
*reading from streams&lt;br /&gt;
&lt;br /&gt;
The last thing is partially wrong, the compiler allows this, but in practice you cannot read all kind of data, it is for example not possible to read predicate values and objects from streams.&lt;br /&gt;
&lt;br /&gt;
Let us return to our priority queue. Now that we have defined the domain that represents the queues, we will also have to declare and implement the suitable operations.&lt;br /&gt;
&lt;br /&gt;
Let us start with the simple ones. First we need an operation to obtain the least element in the queue (i.e. the one with least priority).  This can be declared like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
predicates&lt;br /&gt;
    tryGetLeast_rep : (queue_rep{Priority, Data} Queue) -&amp;gt; tuple{Priority, Data} Least determ.&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The predicate is &amp;lt;vp&amp;gt;determ&amp;lt;/vp&amp;gt; because the queue might be empty. The predicate is a function whose argument is a priority queue and which returns a tuple containing both the &amp;lt;vp&amp;gt;Priority&amp;lt;/vp&amp;gt; and the &amp;lt;vp&amp;gt;Data&amp;lt;/vp&amp;gt;.  It does not remove the element from the queue, because I want to be able to peek at the element without removing it.&lt;br /&gt;
&lt;br /&gt;
The list is sorted with the least element first, so the implementation is trivial:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
clauses&lt;br /&gt;
    tryGetLeast_rep([Least|_]) = Least.&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similarly we need a predicate for removing the least element:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
predicates&lt;br /&gt;
    deleteLeast_rep : (queue_rep{Priority, Data} Queue1) -&amp;gt; queue_rep{Priority, Data} Queue.&lt;br /&gt;
clauses&lt;br /&gt;
    deleteLeast_rep([]) = [].&lt;br /&gt;
    deleteLeast_rep([_Least|Rest]) = Rest.&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, we need an insert predicate:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
predicates&lt;br /&gt;
    insert_rep : (queue_rep{Pri, Data} Q1,  Pri P,  Data D) -&amp;gt; queue_rep{Pri, Data} Q0.&lt;br /&gt;
clauses&lt;br /&gt;
    insert_rep([], Pri, Data) = [tuple(Pri, Data)].&lt;br /&gt;
&lt;br /&gt;
    insert_rep(Q1, Pri, Data) = Q0 :-&lt;br /&gt;
        [tuple(P1,D1)|Rest] = Q1,&lt;br /&gt;
        if Pri &amp;lt;= P1 then&lt;br /&gt;
            Q0 = [tuple(Pri, Data)| Q1]&lt;br /&gt;
        else&lt;br /&gt;
            Q0 =&lt;br /&gt;
                [tuple(P1,D1) | insert_rep(Rest, Pri, Data)]&lt;br /&gt;
        end if.&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
I have chosen shorter variable names to make the code fit the narrow column, but at the same time it gives me the opportunity to explain that type variables like Pri above only have scope in the declaration/definition where they occur.  Therefore, there is nothing wrong with using Priority in one declaration and Pri in another. Nevertheless, you should of course choose variable names with care, because good names make the code clearer. The compiler would not mind if you exchange  Priority and Data, but I am sure that it could confuse many programmers.&lt;br /&gt;
&lt;br /&gt;
The priority queue above can be used for various purposes, but it has two disadvantages, which both relate to the way we have defined the queue domain itself:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
domains&lt;br /&gt;
    queue_rep{Priority, Data} = tuple{Priority, Data}*.&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A definition like this one is just an abbreviation or synonym, so &amp;lt;vp&amp;gt;queue_rep{integer, sting}&amp;lt;/vp&amp;gt; is exactly the same as &amp;lt;vp&amp;gt;tuple{integer, string}*&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
#The debugger will always show the unfolded type (i.e. &amp;lt;vp&amp;gt;tuple{integer, string}*&amp;lt;/vp&amp;gt;) and this can be rather confusing.&lt;br /&gt;
&lt;br /&gt;
#Any piece of data that have this type can accidentally be given as argument to the priority queue predicates. However, the priority queue operations not only require that the data has this type, it also expect that it is sorted in a specific way (i.e. that the data satisfies the invariant).&lt;br /&gt;
&lt;br /&gt;
The latter problem could just as easy exist without polymorphism. It comes from using a general data structure for something specific. If you do this, you can mix anything that is of the general kind even though it is of different specific kinds.&lt;br /&gt;
&lt;br /&gt;
So instead we just consider the queue_rep domain as being the internal &amp;#039;&amp;#039;representation&amp;#039;&amp;#039; of the queues, hence the extension _rep. To the external world we will wrap each queue_rep queue inside a functor.&lt;br /&gt;
&lt;br /&gt;
Therefore, to the real queue domain will look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
domains&lt;br /&gt;
    queue{Priority, Data} = queue(queue_rep{Priority, Data}).&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Such a domain is neither an abbreviation nor a synonym.&lt;br /&gt;
&lt;br /&gt;
The exported/public predicates will of course work on queue &amp;#039;s, so the complete class declaration looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
class priorityQueue&lt;br /&gt;
    open core&lt;br /&gt;
&lt;br /&gt;
domains&lt;br /&gt;
    queue_rep{Priority, Data} = tuple{Priority, Data}*.&lt;br /&gt;
&lt;br /&gt;
domains&lt;br /&gt;
    queue{Priority, Data} = queue(queue_rep{Priority, Data}).&lt;br /&gt;
&lt;br /&gt;
constants&lt;br /&gt;
    empty : queue{Priority, Data} = queue([]).&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    insert : (queue{Pri, Data} Q1, Pri Pri, Data Data) -&amp;gt; queue{Pri, Data} Q0.&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    tryGetLeast : (queue{Priority, Data} Queue) -&amp;gt; tuple{Priority, Data} Least determ.&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    deleteLeast : (queue{Priority, Data} Queue1) -&amp;gt; queue{Priority, Data} Queue.&lt;br /&gt;
end class priorityQueue&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
I have also added an empty queue constant to the class. As a user of the class you then do not need to be concerned with the representation of the queues at all, there are predicates and constants for everything.&lt;br /&gt;
&lt;br /&gt;
The predicates in this class are very simple to implement given the predicates we implemented before, the only thing they should do is to remove and add the queue functor in the relevant places:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
clauses&lt;br /&gt;
    insert(queue(Queue), Priority, Data) = queue(insert_rep(Queue, Priority, Data)).&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    tryGetLeast(queue(Queue)) = tryGetLeast_rep(Queue).&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    deleteLeast(queue(Queue)) = queue(deleteLeast_rep(Queue)).&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Using this _rep scheme is a bit less efficient, because of the extra functor, and it is entirely up to your temperament whether to use it or not. In any case it makes your type unique, rather than being a synonym type.&lt;br /&gt;
&lt;br /&gt;
Priority queues can be used like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
clauses&lt;br /&gt;
    test():-&lt;br /&gt;
        Pq1 = priorityQueue::empty,&lt;br /&gt;
        Pq2 = priorityQueue::insert(Pq1, 17, &amp;quot;World&amp;quot;),&lt;br /&gt;
        Pq3 = priorityQueue::insert(Pq2, 12, &amp;quot;Hello&amp;quot;),&lt;br /&gt;
        Pq4 = priorityQueue::insert(Pq3, 23, &amp;quot;!&amp;quot;),&lt;br /&gt;
        stdio::writef(&amp;quot;%\n&amp;quot;, Pq4).&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The output looks like this (except for additional white space):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
queue( [tuple(12,&amp;quot;Hello&amp;quot;), tuple(17,&amp;quot;World&amp;quot;), tuple(23,&amp;quot;!&amp;quot;) ] )&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It may seem that polymorphism disables type check, but in fact it gives a very strong but flexible type check. If, for example, I write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
clauses&lt;br /&gt;
    test():-&lt;br /&gt;
        Pq1 = priorityQueue::empty,&lt;br /&gt;
        Pq2 = priorityQueue::insert(Pq1, 17, &amp;quot;World&amp;quot;),&lt;br /&gt;
        Pq3 = priorityQueue::insert(Pq2, 12, 13).&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then I will get the error message:&lt;br /&gt;
&lt;br /&gt;
error c504: The expression has type &amp;#039;::integer&amp;#039;, which is incompatible with the type &amp;#039;::string&amp;#039;&lt;br /&gt;
&lt;br /&gt;
The first insert forces the Data type of Pq2 to be string, therefore you cannot use an integer in the next line.&lt;br /&gt;
&lt;br /&gt;
What may be more surprising is that it also forces the Data type of Pq1 to be string. Therefore this code gives exactly the same error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
clauses&lt;br /&gt;
    test():-&lt;br /&gt;
        Pq1 = priorityQueue::empty,&lt;br /&gt;
        Pq2 = priorityQueue::insert(Pq1, 17, &amp;quot;World&amp;quot;),&lt;br /&gt;
        Pq3 = priorityQueue::insert(Pq1, 12, 13).&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
On the other hand this is legal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
clauses&lt;br /&gt;
    test():-&lt;br /&gt;
        Pq1a = priorityQueue::empty,&lt;br /&gt;
        Pq2 = priorityQueue::insert(Pq1a, 17, &amp;quot;World&amp;quot;),&lt;br /&gt;
        Pq1b = priorityQueue::empty,&lt;br /&gt;
        Pq3 = priorityQueue::insert(Pq1b, 12, 13).&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;quot;moral&amp;quot; is that the constant empty is polymorphic, but variables can only have a monomorphic type, so when empty is bound to a variable a concrete type is chosen and &amp;quot;frozen&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
The priority queue above can be use for numerous purposes. And the code can be shared between all such uses, both within a single program and across programs. If I choose to make a more efficient solution to the priority queue, then I will benefit from this in all places where it is used.&lt;br /&gt;
&lt;br /&gt;
Parametric polymorphism is used to solve different problems in the same way (e.g. a using priority queue), and as such it is often used to make basic library software.&lt;br /&gt;
&lt;br /&gt;
Subsumption polymorphism is in many respects the complement to parametric polymorphism: it is used solve the same problem in &amp;#039;&amp;#039; different&amp;#039;&amp;#039; ways (e.g. reporting salaries to &amp;#039;&amp;#039;different&amp;#039;&amp;#039; salary systems), and as such it is often used at high levels in applications to deal with variance.&lt;br /&gt;
&lt;br /&gt;
However, the world is not black and white in this respect, there are many graduations and clear exceptions to this.&lt;br /&gt;
&lt;br /&gt;
=== Example: Job Scheduler ===&lt;br /&gt;
&lt;br /&gt;
Now let us try to combine some of the things from above to produce a simple, but yet powerful &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;job scheduler&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
A &amp;#039;&amp;#039;job&amp;#039;&amp;#039; is just some computation that should be performed. You register a job in the scheduler; the scheduler will then start the job at the requested time. Given such an &amp;quot;alarm clock&amp;quot; scheduler it is relatively easy to deal with reoccurring jobs and jobs that start in X minutes rather than at a certain time, and so forth. Here we will only consider the &amp;quot;alarm clock&amp;quot; functionality.&lt;br /&gt;
&lt;br /&gt;
The scheduler will rely on a timer event: every time the timer even triggers it will see if any jobs are due, and execute these.&lt;br /&gt;
&lt;br /&gt;
In this example I will just assume that time is an integer. I might want to use several schedulers in my program, so I choose to represent each scheduler by an object. Therefore the scheduler is mainly described as an interface, i.e. the type of the scheduler objects. The declaration of the scheduler looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
interface scheduler&lt;br /&gt;
domains&lt;br /&gt;
    job = (integer Time) procedure (i).&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    registerJob : (integer Time, job Job).&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    timerTick : (integer Time).&lt;br /&gt;
end interface scheduler&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A job is a predicate value acting as a callback. I have chosen that the job receive the invocation Time as a parameter. This is mainly for illustrative purposes and simplicity. In real life, I would probably rather give it the scheduler, which I would enrich with predicates for obtaining the current time and probably other things as well. That way the job can itself decide which information it wants to obtain.&lt;br /&gt;
&lt;br /&gt;
registerJob has the obvious functionality.&lt;br /&gt;
&lt;br /&gt;
timerTick should be invoked regularly, since this is the heart of the scheduler.&lt;br /&gt;
&lt;br /&gt;
The implementation looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
implement scheduler&lt;br /&gt;
    open core, priorityQueue&lt;br /&gt;
facts&lt;br /&gt;
    jobQueue : queue{integer, job}.&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    new() :-&lt;br /&gt;
        jobQueue := empty.&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    registerJob(Time, Job) :-&lt;br /&gt;
        jobQueue := insert(jobQueue, Time, Job).&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    timerTick(Time) :-&lt;br /&gt;
        if&lt;br /&gt;
            tuple(T, Job) = tryGetLeast(jobQueue),&lt;br /&gt;
            T &amp;lt;= Time&lt;br /&gt;
        then&lt;br /&gt;
            Job(Time),&lt;br /&gt;
            jobQueue := deleteLeast(jobQueue),&lt;br /&gt;
            timerTick(Time)&lt;br /&gt;
        end if.&lt;br /&gt;
end implement scheduler&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Most of the implementation is completely trivial. The main thing is that I use a priority internally for storing the jobs, with the time as priority. This have the advantage that the &amp;quot;most due&amp;quot; job is always easily accessible.&lt;br /&gt;
&lt;br /&gt;
There is a jobQueue fact that is initialized in the constructor, and registerJob simply insert the job in the priority queue.&lt;br /&gt;
&lt;br /&gt;
The important things take place in timerTick. It peek at the &amp;quot;least&amp;quot; job in the queue. If this hob should be started now or earlier then it is stated and removed from the queue, and then the rest of the queue is considered.&lt;br /&gt;
&lt;br /&gt;
If the &amp;quot;least&amp;quot; job is not due then we do nothing, i.e. then we wait for another timer tick.&lt;br /&gt;
&lt;br /&gt;
Before we use the scheduler I want to point out that several good reasons why the scheduler does not contain the actual timer:&lt;br /&gt;
&lt;br /&gt;
*It may be important to be in synchronization with some external clock&lt;br /&gt;
&lt;br /&gt;
*In some contexts the increment in the Time parameter need not be the same al the time&lt;br /&gt;
&lt;br /&gt;
*In some contexts the Time does not relate to real time. (E.g. game steps, workflow steps., etc).&lt;br /&gt;
&lt;br /&gt;
*In a GUI application it may be important that the timerTick&amp;#039;s are invoked from a window event. I.e. to keep the application single threaded.&lt;br /&gt;
&lt;br /&gt;
Using external timer ticks makes all this possible.&lt;br /&gt;
&lt;br /&gt;
Let us use the timer in a console program, where the clock is provided by a simple for loop:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
class predicates&lt;br /&gt;
    traceJob : (integer Time).&lt;br /&gt;
clauses&lt;br /&gt;
    traceJob(Time) :-&lt;br /&gt;
        stdio::write(&amp;quot;Now: &amp;quot;, Time, &amp;quot;\n&amp;quot;).&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    test() :-&lt;br /&gt;
        Scheduler = scheduler::new(),&lt;br /&gt;
        Scheduler:registerJob(500, traceJob),&lt;br /&gt;
        foreach Time = std::fromTo(1,1000) do&lt;br /&gt;
            Scheduler:timerTick(Time)&lt;br /&gt;
        end foreach.&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The traceJob simply writes the clock. We create a scheduler and register the traceJob for running at Time = 500, and then we start the clock.&lt;br /&gt;
&lt;br /&gt;
We can also make a job that reschedules itself and thus runs repeatedly. To do this the job must have access to the scheduler and therefore we save it in a fact:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
class predicates&lt;br /&gt;
    cyclicJob : (integer Time).&lt;br /&gt;
clauses&lt;br /&gt;
    cyclicJob(Time) :-&lt;br /&gt;
        stdio::write(&amp;quot;Hello World!\n&amp;quot;),&lt;br /&gt;
        scheduler:registerJob(Time+50, cyclicJob).&lt;br /&gt;
&lt;br /&gt;
class facts&lt;br /&gt;
    scheduler : scheduler := erroneous.&lt;br /&gt;
clauses&lt;br /&gt;
    test() :-&lt;br /&gt;
        scheduler := scheduler::new(),&lt;br /&gt;
        scheduler:registerJob(5, cyclicJob),&lt;br /&gt;
        foreach Time = std::fromTo(1,200) do&lt;br /&gt;
            scheduler:timerTick(Time)&lt;br /&gt;
        end foreach.&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the scheduler we have clearly used the (parametric) polymorphic priority queue. We have also used the (subsumption) polymorphism that comes from predicate values, such that we can register jobs with different implementation in the scheduler. The parametric polymorphism has exploited the homogeneous treatment of prioritizing things, no matter which kind of things we are dealing with. The subsumption polymorphism has been used to deal with the heterogeneous nature of jobs themselves.&lt;br /&gt;
&lt;br /&gt;
[[ru:Объекты и полиморфизм. Ч.1]]&lt;/div&gt;</summary>
		<author><name>Kasper B H Petersen</name></author>
	</entry>
	<entry>
		<id>https://wiki.visual-prolog.com/index.php?title=Lists_and_Recursion&amp;diff=4835</id>
		<title>Lists and Recursion</title>
		<link rel="alternate" type="text/html" href="https://wiki.visual-prolog.com/index.php?title=Lists_and_Recursion&amp;diff=4835"/>
		<updated>2021-10-11T12:42:10Z</updated>

		<summary type="html">&lt;p&gt;Kasper B H Petersen: /* Finding All the Solutions at Once */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;List processing – handling sequences of elements – is a powerful technique in Prolog. In this tutorial, we explain what lists are and how to declare them, and then give several examples that show how you might use list processing in your own applications. We also define two well known Prolog predicates – member and append – while looking at list processing from both a recursive and a procedural standpoint.&lt;br /&gt;
&lt;br /&gt;
After that, we introduce findall, a Visual Prolog standard predicate that enables you to find and collect all solutions to a single goal. We round out this tutorial with a discussion of compound lists – combinations of different types of elements – and an example of parsing by difference lists.&lt;br /&gt;
&lt;br /&gt;
==What Is a List?==&lt;br /&gt;
&lt;br /&gt;
In Prolog, &amp;#039;&amp;#039;a list&amp;#039;&amp;#039; is an object that contains an arbitrary number of other objects within it. Lists correspond roughly to arrays in other languages, but, unlike an array, a list does not require you to declare how big it will be before you use it.&lt;br /&gt;
&lt;br /&gt;
A list that contains the numbers &amp;lt;vp&amp;gt;1&amp;lt;/vp&amp;gt;, &amp;lt;vp&amp;gt;2&amp;lt;/vp&amp;gt;, and &amp;lt;vp&amp;gt;3&amp;lt;/vp&amp;gt; is written as&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;[1, 2, 3]&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The order of the elements in this list matters:&lt;br /&gt;
&lt;br /&gt;
*Number &amp;quot;1&amp;quot; is the first element,&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;2&amp;quot; - the second,&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;3&amp;quot; - the third.&lt;br /&gt;
&lt;br /&gt;
The list &amp;lt;vp&amp;gt;[1, 2, 3]&amp;lt;/vp&amp;gt; is different from the list &amp;lt;vp&amp;gt;[1, 3, 2]&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Each item contained in the list is known as an element. To form a list data structure, you separate the elements of a list with commas and then enclose them in square brackets. Here are some examples:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;[&amp;quot;dog&amp;quot;, &amp;quot;cat&amp;quot;, &amp;quot;canary&amp;quot;]&lt;br /&gt;
[&amp;quot;valerie ann&amp;quot;, &amp;quot;jennifer caitlin&amp;quot;, &amp;quot;benjamin thomas&amp;quot;]&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The same element can be present in the list several times, for example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;[1, 2, 1, 3, 1]&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Lists Domains ==&lt;br /&gt;
&lt;br /&gt;
It &amp;lt;vp&amp;gt;T&amp;lt;/vp&amp;gt; is a type/domain then &amp;lt;vp&amp;gt;T*&amp;lt;/vp&amp;gt; is the domain of lists containing &amp;lt;vp&amp;gt;T&amp;lt;/vp&amp;gt; elements.  I.e. an asterisk after a domain means &amp;quot;List of that domain&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
The elements in a list can be anything, including other lists. However, all elements in a list must belong to the &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;same&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039; domain.&lt;br /&gt;
 &lt;br /&gt;
== Heads and Tails ==&lt;br /&gt;
&lt;br /&gt;
A list is really a recursive compound object. It consists of two parts: the head, of a list, which is the first element, and the tail, which is a list comprising all the subsequent elements.&lt;br /&gt;
&lt;br /&gt;
The tail of a list is always a list; the head of a list is an element.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;the head of [a, b, c] is a&lt;br /&gt;
the tail of [a, b, c] is [b, c]&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What happens when you get down to a one-element list? The answer is that:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;the head of [c] is c&lt;br /&gt;
the tail of [c] is []&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you take the first element from the tail of a list enough times, you will eventually get down to an empty list (&amp;lt;vp&amp;gt;[]&amp;lt;/vp&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
The empty list cannot be broken into head and tail.&lt;br /&gt;
&lt;br /&gt;
This means that, conceptually, lists have a tree structure just like other compound objects. The tree structure of [a, b, c, d] is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;    list&lt;br /&gt;
   /    \&lt;br /&gt;
  a    list&lt;br /&gt;
      /    \&lt;br /&gt;
     b    list&lt;br /&gt;
         /    \&lt;br /&gt;
        c    list&lt;br /&gt;
            /    \&lt;br /&gt;
           d      []&amp;lt;/pre&amp;gt;Further, a one-element list such as [a] is not the same as the element that it contains, because [a] is really the compound data structure shown here:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;    list&lt;br /&gt;
   /    \&lt;br /&gt;
  a     []&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==List Processing==&lt;br /&gt;
&lt;br /&gt;
Prolog provides a way to make a head and a tail of a list explicit. Instead of separating elements with commas, you can separate the head and tail with a vertical bar (|). For instance,&lt;br /&gt;
&amp;lt;vip&amp;gt;[a, b, c]&amp;lt;/vip&amp;gt;&lt;br /&gt;
is equivalent to&lt;br /&gt;
&amp;lt;vip&amp;gt;[a | [b, c]]&amp;lt;/vip&amp;gt;&lt;br /&gt;
which continuing the process is equivalent to &lt;br /&gt;
&amp;lt;vip&amp;gt;[a | [b | [c]]]&amp;lt;/vip&amp;gt;&lt;br /&gt;
which is equivalent to&lt;br /&gt;
&amp;lt;vip&amp;gt;[a | [b | [c | []]]]&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can even use both kinds of separators in the same list, provided the vertical bar is the last separator. So, if you really want to, you can write [a, b, c, d] as [a, b|[c, d]].&lt;br /&gt;
&lt;br /&gt;
Table 1 gives more examples.&lt;br /&gt;
{|cellpadding=&amp;quot;50&amp;quot; cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
|+&amp;#039;&amp;#039;&amp;#039;Table 1: Heads and Tails of Lists&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
! List&lt;br /&gt;
! Head&lt;br /&gt;
! Tail&lt;br /&gt;
|-&lt;br /&gt;
| [&amp;#039;a&amp;#039;, &amp;#039;b&amp;#039;, &amp;#039;c&amp;#039;]&lt;br /&gt;
| &amp;#039;a&amp;#039;&lt;br /&gt;
| [&amp;#039;b&amp;#039;, &amp;#039;c&amp;#039;]&lt;br /&gt;
|-&lt;br /&gt;
| [&amp;#039;a&amp;#039;]&lt;br /&gt;
| &amp;#039;a&amp;#039;&lt;br /&gt;
| [] &lt;br /&gt;
|-&lt;br /&gt;
| []&lt;br /&gt;
| does not exist&lt;br /&gt;
| does not exist&lt;br /&gt;
|-&lt;br /&gt;
| [[1, 2, 3], [2, 3, 4], []]&lt;br /&gt;
| [1, 2, 3]&lt;br /&gt;
| [[2, 3, 4], []]&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Table 2 gives several examples of list unification.&lt;br /&gt;
&lt;br /&gt;
{|cellpadding=&amp;quot;5&amp;quot; cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
|+&amp;#039;&amp;#039;&amp;#039;Table 2: Unification of Lists&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
!List 1&lt;br /&gt;
!List 2&lt;br /&gt;
!Variable Binding&lt;br /&gt;
|-&lt;br /&gt;
|[X, Y, Z]&lt;br /&gt;
|[egbert, eats, icecream]&lt;br /&gt;
|X=egbert, Y=eats, Z=icecream&lt;br /&gt;
|-&lt;br /&gt;
|[7]&lt;br /&gt;
|[X &amp;lt;nowiki&amp;gt;|&amp;lt;/nowiki&amp;gt; Y] &lt;br /&gt;
|X=7, Y=[]&lt;br /&gt;
|-&lt;br /&gt;
|[1, 2, 3, 4]&lt;br /&gt;
|[X, Y &amp;lt;nowiki&amp;gt;|&amp;lt;/nowiki&amp;gt; Z]&lt;br /&gt;
|X=1, Y=2, Z=[3,4]&lt;br /&gt;
|-&lt;br /&gt;
|[1, 2]&lt;br /&gt;
|[3 &amp;lt;nowiki&amp;gt;|&amp;lt;/nowiki&amp;gt; X]&lt;br /&gt;
|fail&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Using Lists ==&lt;br /&gt;
&lt;br /&gt;
Because a list is really a recursive compound data structure, you need recursive algorithms to process it. The most basic way to process a list is to work through it, doing something to each element until you reach the end.&lt;br /&gt;
&lt;br /&gt;
An algorithm of this kind usually needs two clauses. One of them says what to do with an ordinary list (one that can be divided into a head and a tail). The other says what to do with an empty list.&lt;br /&gt;
&lt;br /&gt;
=== Writing Lists ===&lt;br /&gt;
&lt;br /&gt;
For example, if you just want to print out the elements of the list, here is what you do:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;implement main&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    run() :-&lt;br /&gt;
        write_a_list([1, 2, 3]).&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    write_a_list : (integer* List).&lt;br /&gt;
clauses&lt;br /&gt;
    write_a_list([]).&lt;br /&gt;
        /* If the list is empty, do nothing more. */&lt;br /&gt;
    write_a_list([H | T]) :-&lt;br /&gt;
        /* Match the head to H and the tail to T, then... */&lt;br /&gt;
        stdio::write(H),&lt;br /&gt;
        stdio::nl,&lt;br /&gt;
        write_a_list(T).&lt;br /&gt;
&lt;br /&gt;
end implement main&lt;br /&gt;
&lt;br /&gt;
goal&lt;br /&gt;
    console::runUtf8(main::run).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here are the two write_a_list clauses described in natural language:&lt;br /&gt;
&lt;br /&gt;
*To write an empty list, do nothing.&lt;br /&gt;
*Otherwise, to write a list, write its head (which is a single element), then write its tail (a list).&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;vp&amp;gt;write_a_list&amp;lt;/vp&amp;gt; predicate is called from &amp;lt;vp&amp;gt;run&amp;lt;/vp&amp;gt; clause:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;write_a_list([1, 2, 3])&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This matches the second clause, with H=1 and T=[2, 3]; this writes 1 and then calls write_a_list recursively with the tail of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;write_a_list([2, 3]).&lt;br /&gt;
    /* This is write_a_list(T). */&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This recursive call matches the second clause, this time with H=2 and T=[3], so it writes 2 and again calls write_a_list recursively:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;write_a_list([3]).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now, which clause will this goal match? Recall that, even though the list [3] has only one element; it does have a head and tail; the head is 3 and the tail is []. So, again the goal matches the second clause, with H=3 and T=[]. Hence, 3 is written and write_a_list is called recursively like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;write_a_list([]).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now you see why this program needs the first clause. The second clause will not match this goal because [] cannot be divided into head and tail. So, if the first clause were not there, the goal would fail. As it is, the first clause matches and the goal succeeds without doing anything further.&lt;br /&gt;
&lt;br /&gt;
===Counting List Elements===&lt;br /&gt;
&lt;br /&gt;
Now consider how you might find out how many elements are in a list. What is the length of a list, anyway? Here is a simple logical definition:&lt;br /&gt;
&lt;br /&gt;
*The length of an empty list, &amp;lt;vp&amp;gt;[]&amp;lt;/vp&amp;gt;, is &amp;lt;vp&amp;gt;0&amp;lt;/vp&amp;gt;.&amp;lt;br /&amp;gt;&lt;br /&gt;
*The length of any other list is the length of its tail plus &amp;lt;vp&amp;gt;1&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Can you implement this? In Prolog it is very easy. It takes just two clauses:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;class main&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    length_of : (A* List) -&amp;gt; integer Length.&lt;br /&gt;
&lt;br /&gt;
end class&lt;br /&gt;
&lt;br /&gt;
implement main&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    length_of([]) = 0.&lt;br /&gt;
    length_of([_ | T]) = Length :-&lt;br /&gt;
        TailLength = length_of(T),&lt;br /&gt;
        Length = TailLength + 1.&lt;br /&gt;
&lt;br /&gt;
end implement main&lt;br /&gt;
&lt;br /&gt;
goal&lt;br /&gt;
    console::init(),&lt;br /&gt;
    Length = main::length_of([1, 2, 3]),&lt;br /&gt;
    stdio::write(Length).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Take a look at the second clause first. Crucially, &amp;lt;vp&amp;gt;[_ | T]&amp;lt;/vp&amp;gt; will match any nonempty list, binding &amp;lt;vp&amp;gt;T&amp;lt;/vp&amp;gt; to the tail of the list. The value of the head is unimportant; as long as it exists, it can be counted it as one element.&lt;br /&gt;
&lt;br /&gt;
So the goal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;Length = main::length_of([1, 2, 3])&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
will match the second clause, with &amp;lt;vp&amp;gt;T&amp;lt;/vp&amp;gt; = &amp;lt;vp&amp;gt;[2, 3]&amp;lt;/vp&amp;gt;. The next step is to compute the length of &amp;lt;vp&amp;gt;T&amp;lt;/vp&amp;gt;. When this is done (never mind how), &amp;lt;vp&amp;gt;TailLength&amp;lt;/vp&amp;gt; will get the value &amp;lt;vp&amp;gt;2&amp;lt;/vp&amp;gt;, and the computer can then add &amp;lt;vp&amp;gt;1&amp;lt;/vp&amp;gt; to it and bind &amp;lt;vp&amp;gt;Length&amp;lt;/vp&amp;gt; to &amp;lt;vp&amp;gt;3&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
So how is the middle step executed? That step was to find the length of &amp;lt;vp&amp;gt;[2, 3]&amp;lt;/vp&amp;gt; by satisfying the goal&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;TailLength = main::length_of([2, 3])&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In other words, &amp;lt;vp&amp;gt;length_of&amp;lt;/vp&amp;gt; calls itself recursively. This goal matches the second clause, binding&lt;br /&gt;
&lt;br /&gt;
*&amp;lt;vp&amp;gt;[3]&amp;lt;/vp&amp;gt; in the goal to &amp;lt;vp&amp;gt;T&amp;lt;/vp&amp;gt; in the clause and&lt;br /&gt;
*&amp;lt;vp&amp;gt;TailLength&amp;lt;/vp&amp;gt; in the goal to &amp;lt;vp&amp;gt;Length&amp;lt;/vp&amp;gt; in the clause.&lt;br /&gt;
&lt;br /&gt;
Recall that &amp;lt;vp&amp;gt;TailLength&amp;lt;/vp&amp;gt; in the goal will not interfere with &amp;lt;vp&amp;gt;TailLength&amp;lt;/vp&amp;gt; in the clause, because &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;each recursive invocation of a clause has its own set of variables&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
So now the problem is to find the length of &amp;lt;vp&amp;gt;[3]&amp;lt;/vp&amp;gt;, which will be &amp;lt;vp&amp;gt;1&amp;lt;/vp&amp;gt;, and then add &amp;lt;vp&amp;gt;1&amp;lt;/vp&amp;gt; to that to get the length of &amp;lt;vp&amp;gt;[2, 3]&amp;lt;/vp&amp;gt;, which will be &amp;lt;vp&amp;gt;2&amp;lt;/vp&amp;gt;. So far, so good.&lt;br /&gt;
&lt;br /&gt;
Likewise, &amp;lt;vp&amp;gt;length_of&amp;lt;/vp&amp;gt; will call itself recursively again to get the length of &amp;lt;vp&amp;gt;[3]&amp;lt;/vp&amp;gt;. The tail of &amp;lt;vp&amp;gt;[3]&amp;lt;/vp&amp;gt; is &amp;lt;vp&amp;gt;[]&amp;lt;/vp&amp;gt;, so &amp;lt;vp&amp;gt;T&amp;lt;/vp&amp;gt; is bound to &amp;lt;vp&amp;gt;[]&amp;lt;/vp&amp;gt;, and the problem is to get the length of &amp;lt;vp&amp;gt;[]&amp;lt;/vp&amp;gt;, then add 1 to it, giving the length of &amp;lt;vp&amp;gt;[3]&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
This time it&amp;#039;s easy. The goal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;TailLength = main::length_of([])&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
matches the &amp;#039;&amp;#039;first&amp;#039;&amp;#039; clause, binding &amp;lt;vp&amp;gt;TailLength&amp;lt;/vp&amp;gt; to &amp;lt;vp&amp;gt;0&amp;lt;/vp&amp;gt;. So now the computer can add &amp;lt;vp&amp;gt;1&amp;lt;/vp&amp;gt; to that, giving the length of &amp;lt;vp&amp;gt;[3]&amp;lt;/vp&amp;gt;, and return to the calling clause. This, in turn, will add &amp;lt;vp&amp;gt;1&amp;lt;/vp&amp;gt; again, giving the length of &amp;lt;vp&amp;gt;[2, 3]&amp;lt;/vp&amp;gt;, and return to the clause that called it; this original clause will add &amp;lt;vp&amp;gt;1&amp;lt;/vp&amp;gt; again, giving the length of &amp;lt;vp&amp;gt;[1, 2, 3]&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Confused yet? We hope not. In the following brief illustration we&amp;#039;ll summarize the calls. We&amp;#039;ve used suffixes to indicate that similarly named variables in different clauses – or different invocations of the same clause – are distinct. Please notice that you do not need to implement such predicate in your own code, you can use &amp;#039;&amp;#039;&amp;#039;list::length&amp;#039;&amp;#039;&amp;#039; predicate from PFC.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;Length_1 = main::length_of([1, 2, 3]).&lt;br /&gt;
    TailLength_1 = main::length_of([2, 3]).&lt;br /&gt;
        TailLength_2 = main::length_of([3]).&lt;br /&gt;
            TailLength_3 = main::length_of([]).&lt;br /&gt;
            TailLength_3 = 0.&lt;br /&gt;
        Length_3 =  TailLength_3 + 1 = 1.&lt;br /&gt;
    Length_2 = Length_3 + 1 = 2.&lt;br /&gt;
Length_1 = Length_2 + 1 = 3.&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that the code above can be written more compact without the use of intermediate variables like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;&lt;br /&gt;
clauses&lt;br /&gt;
    length_of([]) = 0.&lt;br /&gt;
    length_of([_ | T]) = length_of(T) + 1.&lt;br /&gt;
&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
These clauses more or less directly states the original specification:&lt;br /&gt;
&lt;br /&gt;
*The length of an empty list, &amp;lt;vp&amp;gt;[]&amp;lt;/vp&amp;gt;, is &amp;lt;vp&amp;gt;0&amp;lt;/vp&amp;gt;.&amp;lt;br /&amp;gt;&lt;br /&gt;
*The length of any other list is the length of its tail plus &amp;lt;vp&amp;gt;1&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Tail Recursion===&lt;br /&gt;
&lt;br /&gt;
You probably noticed that &amp;lt;vp&amp;gt;length_of&amp;lt;/vp&amp;gt; is not, and can&amp;#039;t be, tail-recursive, because the recursive call is not the last step in its clause. Can you create a tail-recursive list-length predicate? Yes, but it will take some effort.&lt;br /&gt;
&lt;br /&gt;
The problem with &amp;lt;vp&amp;gt;length_of&amp;lt;/vp&amp;gt; is that you can&amp;#039;t compute the length of a list until you&amp;#039;ve already computed the length of the tail. It turns out there&amp;#039;s a way around this. You&amp;#039;ll need a list-length predicate with two arguments.&lt;br /&gt;
&lt;br /&gt;
* The first is the list, which the computer will whittle away on each call until it eventually becomes empty, just as before.&lt;br /&gt;
* The second is an counter that starts out as &amp;lt;vp&amp;gt;0&amp;lt;/vp&amp;gt; and increments on each call.&lt;br /&gt;
&lt;br /&gt;
When the list is finally empty, you&amp;#039;ll return the counter as the list length.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;class main&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    length_of : (A* List, integer Counter) -&amp;gt; integer Result.&lt;br /&gt;
&lt;br /&gt;
end class&lt;br /&gt;
&lt;br /&gt;
implement main&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    length_of([], Counter) = Counter.&lt;br /&gt;
    length_of([_ | T], Counter) = Result :-&lt;br /&gt;
        NewCounter = Counter + 1,&lt;br /&gt;
        Result = length_of(T, NewCounter).&lt;br /&gt;
&lt;br /&gt;
end implement main&lt;br /&gt;
&lt;br /&gt;
goal&lt;br /&gt;
    console::init(),&lt;br /&gt;
    main::length_of([1, 2, 3], L, 0), /* start with Counter = 0 */&lt;br /&gt;
    stdio::write(&amp;quot; L = &amp;quot;, L).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This version of the &amp;lt;vp&amp;gt;length_of&amp;lt;/vp&amp;gt; predicate is more complicated, and in many ways less logical, than the previous one. We&amp;#039;ve presented it merely to show you that, &amp;#039;&amp;#039;by devious means, you can often find a tail-recursive algorithm for a problem that seems to demand a different type of recursion&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
=== Another Example – Modifying the List ===&lt;br /&gt;
&lt;br /&gt;
Sometimes you want to take a list and create another list from it. You do this by working through the list element by element, replacing each element with a computed value. For example, here is a program that takes a list of numbers and adds 1 to each of them:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;class main&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    add1 : (integer* NumberList) -&amp;gt; integer* IncrList.&lt;br /&gt;
&lt;br /&gt;
end class&lt;br /&gt;
&lt;br /&gt;
implement main&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    add1([]) = []. % boundary condition&lt;br /&gt;
    add1([Head | Tail]) = Result :-&lt;br /&gt;
        % separate the head  from the rest of the list&lt;br /&gt;
        Head1 = Head + 1, % add 1 to the first element&lt;br /&gt;
        Tail1 = add1(Tail), % call element with the rest of the list&lt;br /&gt;
        Result = [Head1 | Tail1]. % Put the new head infront of the new tail&lt;br /&gt;
&lt;br /&gt;
end implement main&lt;br /&gt;
&lt;br /&gt;
goal&lt;br /&gt;
    console::init(),&lt;br /&gt;
    NewList = main::add1([1, 2, 3, 4]),&lt;br /&gt;
    stdio::write(NewList).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To paraphrase this in natural language:&lt;br /&gt;
&lt;br /&gt;
To add 1 to all the elements of the empty list,&amp;lt;br /&amp;gt;&lt;br /&gt;
just produce another empty list.&amp;lt;br /&amp;gt;&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
To add 1 to all the elements of any other list,&amp;lt;br /&amp;gt;&lt;br /&gt;
add 1 to the head and make it the head of the result, and then&amp;lt;br /&amp;gt;&lt;br /&gt;
add 1 to each element of the tail and make that the tail of the result.&lt;br /&gt;
&lt;br /&gt;
Runnig the the predicate with &amp;lt;vp&amp;gt;[1, 2, 3, 4]&amp;lt;/vp&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;NewList = add1([1,2,3,4]).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Will result in &lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;NewList = [2, 3, 4, 5]&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Tail Recursion Again ===&lt;br /&gt;
&lt;br /&gt;
Is &amp;lt;vp&amp;gt;add1&amp;lt;/vp&amp;gt; tail-recursive? If you&amp;#039;re accustomed to using Lisp or Pascal, you might think it isn&amp;#039;t, because you think of it as performing the following operations:&lt;br /&gt;
&lt;br /&gt;
*Split the list into &amp;lt;vp&amp;gt;Head&amp;lt;/vp&amp;gt; and &amp;lt;vp&amp;gt;Tail&amp;lt;/vp&amp;gt;.&lt;br /&gt;
*Add &amp;lt;vp&amp;gt;1&amp;lt;/vp&amp;gt; to &amp;lt;vp&amp;gt;Head&amp;lt;/vp&amp;gt;, giving &amp;lt;vp&amp;gt;Head1&amp;lt;/vp&amp;gt;.&lt;br /&gt;
*Recursively add 1 to all the elements of &amp;lt;vp&amp;gt;Tail&amp;lt;/vp&amp;gt;, giving &amp;lt;vp&amp;gt;Tail1&amp;lt;/vp&amp;gt;.&lt;br /&gt;
*Combine &amp;lt;vp&amp;gt;Head1&amp;lt;/vp&amp;gt; and &amp;lt;vp&amp;gt;Tail1&amp;lt;/vp&amp;gt;, giving the resulting list.&lt;br /&gt;
&lt;br /&gt;
This isn&amp;#039;t tail-recursive, because the recursive call is not the last step.&lt;br /&gt;
&lt;br /&gt;
But – and this is important – &amp;#039;&amp;#039;that is not how Prolog does it&amp;#039;&amp;#039;. In Visual Prolog, &amp;lt;vp&amp;gt;add1&amp;lt;/vp&amp;gt; is tail-recursive, because its steps are really the following:&lt;br /&gt;
&lt;br /&gt;
*Bind the head and tail of the original list to &amp;lt;vp&amp;gt;Head&amp;lt;/vp&amp;gt; and &amp;lt;vp&amp;gt;Tail&amp;lt;/vp&amp;gt;.&lt;br /&gt;
*Bind the head and tail of &amp;lt;vp&amp;gt;Result&amp;lt;/vp&amp;gt; to &amp;lt;vp&amp;gt;Head1&amp;lt;/vp&amp;gt; and &amp;lt;vp&amp;gt;Tail1&amp;lt;/vp&amp;gt;. (&amp;lt;vp&amp;gt;Head1&amp;lt;/vp&amp;gt; and &amp;lt;vp&amp;gt;Tail1&amp;lt;/vp&amp;gt; do not have values yet.)&lt;br /&gt;
*Add &amp;lt;vp&amp;gt;1&amp;lt;/vp&amp;gt; to &amp;lt;vp&amp;gt;Head&amp;lt;/vp&amp;gt;, giving &amp;lt;vp&amp;gt;Head1&amp;lt;/vp&amp;gt;.&lt;br /&gt;
*Recursively add &amp;lt;vp&amp;gt;1&amp;lt;/vp&amp;gt; to all the elements of &amp;lt;vp&amp;gt;Tail&amp;lt;/vp&amp;gt;, giving &amp;lt;vp&amp;gt;Tail1&amp;lt;/vp&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
When this is done, &amp;lt;vp&amp;gt;Head1&amp;lt;/vp&amp;gt; and &amp;lt;vp&amp;gt;Tail1&amp;lt;/vp&amp;gt; are &amp;#039;&amp;#039;already&amp;#039;&amp;#039; the head and tail of &amp;lt;vp&amp;gt;Result&amp;lt;/vp&amp;gt;; there is no separate operation of combining them. So the recursive call really is the last step.&lt;br /&gt;
&lt;br /&gt;
=== More on Modifying Lists ===&lt;br /&gt;
&lt;br /&gt;
Of course, you don&amp;#039;t actually need to put in a replacement for every element. Here&amp;#039;s a program that scans a list of numbers and copies it, leaving out the negative numbers:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;class main&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    discard_negatives : (integer*, integer* [out]).&lt;br /&gt;
&lt;br /&gt;
end class&lt;br /&gt;
&lt;br /&gt;
implement main&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    discard_negatives([], []).&lt;br /&gt;
    discard_negatives([H | T], ProcessedTail) :-&lt;br /&gt;
        H &amp;lt; 0,&lt;br /&gt;
        !, /* If H is negative, just skip it */&lt;br /&gt;
        discard_negatives(T, ProcessedTail).&lt;br /&gt;
    discard_negatives([H | T], [H | ProcessedTail]) :-&lt;br /&gt;
        discard_negatives(T, ProcessedTail).&lt;br /&gt;
&lt;br /&gt;
end implement main &lt;br /&gt;
&lt;br /&gt;
goal&lt;br /&gt;
    console::init(),&lt;br /&gt;
    main::discard_negatives([2, -45, 3, 468], X),&lt;br /&gt;
    stdio::write(X).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, the goal&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;main::discard_negatives([2, -45, 3, 468], X)&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
gives&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;X=[2, 3, 468].&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And here&amp;#039;s a predicate that copies the elements of a list, making each element occur twice:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;clauses&lt;br /&gt;
    doubletalk([], []).&lt;br /&gt;
    doubletalk([H | T], [H, H | DoubledTail]) :-&lt;br /&gt;
        doubletalk(T, DoubledTail).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List Membership===&lt;br /&gt;
&lt;br /&gt;
Suppose you have a list with the names &amp;#039;&amp;#039;John&amp;#039;&amp;#039;, &amp;#039;&amp;#039;Leonard&amp;#039;&amp;#039;, &amp;#039;&amp;#039;Eric&amp;#039;&amp;#039;, and &amp;#039;&amp;#039;Frank&amp;#039;&amp;#039; and would like to use Visual Prolog to investigate if a given name is in this list. In other words, you must express the relation &amp;quot;membership&amp;quot; between two arguments: a name and a list of names. This corresponds to the predicate&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;isMember : (name, name*).&lt;br /&gt;
    /* &amp;quot;name&amp;quot; is a member of &amp;quot;name*&amp;quot; */&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the program below, the first clause investigates the head of the list. If the head of the list is equal to the name you&amp;#039;re searching for, then you can conclude that Name is a member of the list. Since the tail of the list is of no interest, it is indicated by the anonymous variable. Thanks to this first clause, the goal&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;main::isMember(&amp;quot;john&amp;quot;, [&amp;quot;john&amp;quot;, &amp;quot;leonard&amp;quot;, &amp;quot;eric&amp;quot;, &amp;quot;frank&amp;quot;])&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
is satisfied.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;class main&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    isMember : (A, A*) determ.&lt;br /&gt;
&lt;br /&gt;
end class&lt;br /&gt;
&lt;br /&gt;
implement main&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    isMember(Name, [Name | _]) :-&lt;br /&gt;
        !.&lt;br /&gt;
    isMember(Name, [_ | Tail]) :-&lt;br /&gt;
        isMember(Name, Tail).&lt;br /&gt;
&lt;br /&gt;
end implement main&lt;br /&gt;
&lt;br /&gt;
goal&lt;br /&gt;
    console::init(),&lt;br /&gt;
    main::isMember(&amp;quot;john&amp;quot;, [&amp;quot;john&amp;quot;, &amp;quot;leonard&amp;quot;, &amp;quot;eric&amp;quot;, &amp;quot;frank&amp;quot;]),&lt;br /&gt;
    !,&lt;br /&gt;
    stdio::write(&amp;quot;Success&amp;quot;)&lt;br /&gt;
    or&lt;br /&gt;
    stdio::write(&amp;quot;No solution&amp;quot;).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the head of the list is not equal to Name, you need to investigate whether Name can be found in the tail of the list.&lt;br /&gt;
&lt;br /&gt;
In English:&lt;br /&gt;
&lt;br /&gt;
Name is a member of the list if Name is the first element of the list, or&amp;lt;br /&amp;gt;&lt;br /&gt;
Name is a member of the list if Name is a member of the tail.&lt;br /&gt;
&lt;br /&gt;
The second clause of isMember relates to this relationship. In Visual Prolog:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;    isMember(Name, [_ | Tail]) :-&lt;br /&gt;
        isMember(Name, Tail).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Appending One List to Another: Declarative and Procedural Programming===&lt;br /&gt;
&lt;br /&gt;
As given, the member predicate of the program works in two ways. Consider its clauses once again:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;clauses&lt;br /&gt;
    isMember(Name, [Name | _]) :-&lt;br /&gt;
        !.&lt;br /&gt;
    isMember(Name, [_ | Tail]) :-&lt;br /&gt;
        isMember(Name, Tail).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can look at these clauses from two different points of view: declarative and procedural.&lt;br /&gt;
&lt;br /&gt;
*From a declarative viewpoint, the clauses say:Name is a member of a list if the head is equal to Name;&amp;lt;br /&amp;gt;&lt;br /&gt;
if not, Name is a member of the list if it is a member of the tail.&lt;br /&gt;
&lt;br /&gt;
*From a procedural viewpoint, the two clauses could be interpreted as saying:To find a member of a list, find its head;&amp;lt;br /&amp;gt;&lt;br /&gt;
otherwise, find a member of its tail.&lt;br /&gt;
&lt;br /&gt;
These two points of view correspond to the goals&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;member(2, [1, 2, 3, 4]).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;member(X, [1, 2, 3, 4]).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In effect, the first goal asks Visual Prolog to check whether something is true; the second asks Visual Prolog to find all members of the list [1,2,3,4]. Don&amp;#039;t be confused by this. The member predicate is the same in both cases, but its behavior may be viewed from different angles.&lt;br /&gt;
&lt;br /&gt;
=== Recursion from a Procedural Viewpoint ===&lt;br /&gt;
&lt;br /&gt;
The beauty of Prolog is that, often, when you construct the clauses for a predicate from one point of view, they&amp;#039;ll work from the other. To see this duality, in this next example you&amp;#039;ll construct a predicate to append one list to another. You&amp;#039;ll define the predicate append with three arguments:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;append(List1, List2, List3).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This combines List1 and List2 to form List3. Once again you are using recursion (this time from a procedural point of view).&lt;br /&gt;
&lt;br /&gt;
If List1 is empty, the result of appending &amp;#039;&amp;#039; Lis&amp;#039;&amp;#039;t&amp;#039;&amp;#039;1&amp;#039;&amp;#039; and List2 will be the same as List2. In Prolog:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;append([], List2, List2).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If List1 is not empty, you can combine List1 and List2 to form &amp;#039;&amp;#039;List3&amp;#039;&amp;#039; by making the head of List1 the head of List3. (In the following code, the variable H is used as the head of both List1 and List3.) The tail of List3 is L3, which is composed of the rest of List1 (namely, L1) and all of List2. In Prolog:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;append([H | L1], List2, [H | L3]) :-&lt;br /&gt;
    append(L1, List2, L3).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The append predicate operates as follows: While List1 is not empty, the recursive rule transfers one element at a time to List3. When List1 is empty, the first clause ensures that List2 hooks onto the back of List3.&lt;br /&gt;
&lt;br /&gt;
=== One Predicate Can Have Different Uses ===&lt;br /&gt;
&lt;br /&gt;
Looking at append from a declarative point of view, you have defined a relation between three lists. This relation also holds if List1 and List3 are known but List2 isn&amp;#039;t. However, it also holds true if only List3 is known. For example, to find which two lists could be appended to form a known list, you could use a goal of the form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;append(L1, L2, [1, 2, 4]).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With this goal, Visual Prolog will find these solutions:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;1L1=[], L2=[1,2,4]&lt;br /&gt;
L1=[1], L2=[2,4]L1=[1,2], L2=[4]L1=[1,2,4], L2=[]4 Solutions&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use append to find which list you could append to [3,4] to form the list [1,2,3,4]. Try giving the goal&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;append(L1, [3,4], [1,2,3,4]).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Visual Prolog finds the solution&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;L1=[1,2].&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This append predicate has defined a relation between an &amp;#039;&amp;#039; input set&amp;#039;&amp;#039; and an &amp;#039;&amp;#039;output set&amp;#039;&amp;#039; in such a way that the relation applies both ways. Given that relation, you can ask&lt;br /&gt;
&lt;br /&gt;
Which output corresponds to this given input?&lt;br /&gt;
&lt;br /&gt;
or&lt;br /&gt;
&lt;br /&gt;
Which input corresponds to this given output?&lt;br /&gt;
&lt;br /&gt;
The status of the arguments to a given predicate when you call that predicate is referred to as a &amp;#039;&amp;#039;flow pattern&amp;#039;&amp;#039;. An argument that is bound or instantiated at the time of the call is an input argument, signified by (i); a free argument is an output argument, signified by (o).&lt;br /&gt;
&lt;br /&gt;
The append predicate has the ability to handle any flow pattern you provide. However, not all predicates have the capability of being called with different flow patterns. When a Prolog clause is able to handle multiple flow patterns, it is known as an invertible clause. Many of list predicate can be found in the &amp;#039;&amp;#039;&amp;#039;list&amp;#039;&amp;#039;&amp;#039; class.&lt;br /&gt;
&lt;br /&gt;
==Finding All the Solutions at Once==&lt;br /&gt;
&lt;br /&gt;
Backtracking and recursion are two ways to perform repetitive processes. Recursion won out because, unlike backtracking, it can pass information (through arguments) from one recursive call to the next. Because of this, a recursive procedure can keep track of partial results or counters as it goes along.&lt;br /&gt;
&lt;br /&gt;
But there&amp;#039;s one thing backtracking can do that recursion can&amp;#039;t do – namely, find all the alternative solutions to a goal. So you may find yourself in a quandary: You need all the solutions to a goal, but you need them all at once, as part of a single compound data structure. What do you do?&lt;br /&gt;
&lt;br /&gt;
Fortunately, Visual Prolog provides a way out of this impasse. The built-in construction list comprehension takes a goal as one of its arguments and collects all of the solutions to that goal into an output single list. list comprehension takes two arguments:&lt;br /&gt;
&lt;br /&gt;
*The first argument, VarName, specifies which argument in the specified predicate is to be collected into a list.&lt;br /&gt;
&lt;br /&gt;
*The second, mypredicate, indicates the predicate from which the values will be collected.&lt;br /&gt;
&lt;br /&gt;
*The output ListParam, is a variable that holds the list of values collected through backtracking.&lt;br /&gt;
&lt;br /&gt;
This program uses list comprehension to print the average age of a group of people.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;class main&lt;br /&gt;
&lt;br /&gt;
domains&lt;br /&gt;
    name = string.&lt;br /&gt;
    address = string.&lt;br /&gt;
    age = integer.&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    person : (name Name [out], address Address [out], age Age [out]) multi.&lt;br /&gt;
    sumlist : (age* AgeList, age Age [out], integer Count [out]).&lt;br /&gt;
&lt;br /&gt;
end class&lt;br /&gt;
&lt;br /&gt;
implement main&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    sumlist([], 0, 0).&lt;br /&gt;
    sumlist([H | T], Sum, N) :-&lt;br /&gt;
        sumlist(T, S1, N1),&lt;br /&gt;
        Sum = H + S1,&lt;br /&gt;
        N = 1 + N1.&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    person(&amp;quot;Sherlock Holmes&amp;quot;, &amp;quot;22B Baker Street&amp;quot;, 42).&lt;br /&gt;
    person(&amp;quot;Pete Spiers&amp;quot;, &amp;quot;Apt. 22, 21st Street&amp;quot;, 36).&lt;br /&gt;
    person(&amp;quot;Mary Darrow&amp;quot;, &amp;quot;Suite 2, Omega Home&amp;quot;, 51).&lt;br /&gt;
&lt;br /&gt;
end implement main&lt;br /&gt;
&lt;br /&gt;
goal&lt;br /&gt;
    console::init(),&lt;br /&gt;
    L = [Age || main::person(_, _, Age)],&lt;br /&gt;
    main::sumlist(L, Sum, N),&lt;br /&gt;
    Average = Sum / N,&lt;br /&gt;
    stdio::writef(&amp;quot;Average = %.&amp;quot;, Average).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The list comprehension clause in this program creates a list L, which is a collection of all the ages obtained from the predicate person. If you wanted to collect a list of all the people who are 42 years old, you could give the following subgoal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;List = [Who || main::person(Who, _, 42)]&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following code will create the list of positive items:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;List = [X || X in [2,-8,-3,6], X &amp;gt; 0]&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Compound Lists==&lt;br /&gt;
&lt;br /&gt;
A list of integers can be simply declared as&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;integer*&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The same is true for a list of real numbers, a list of symbols, or a list of strings.&lt;br /&gt;
&lt;br /&gt;
However, it is often valuable to store a combination of different types of elements within a list, such as:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;[2, 3, 5.12, [&amp;quot;food&amp;quot;, &amp;quot;goo&amp;quot;], &amp;quot;new&amp;quot;] % Not correct Visual Prolog&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;Compound lists&amp;#039;&amp;#039; are lists that contain more than one type of element. You need special declarations to handle lists of multiple-type elements, because Visual Prolog requires that all elements in a list belong to the &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;same&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039; domain. The way to create a list in Prolog that stores these different types of elements is to use functors, because a domain can contain &amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039;more than one&amp;#039;&amp;#039;&amp;#039;&amp;#039;&amp;#039; data type as arguments to functors.&lt;br /&gt;
&lt;br /&gt;
The following is an example of a domain declaration for a list that can contain an integer, a character, a string, or a list of any of these:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;domains&lt;br /&gt;
    llist = l(list); i(integer); c(char); s(string).&lt;br /&gt;
        % the functors are l, i, c, and s&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The list&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;[2, 9, [&amp;quot;food&amp;quot;, &amp;quot;goo&amp;quot;], &amp;quot;new&amp;quot;] % Not correct Visual Prolog&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
would be written in Visual Prolog as:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;[i(2), i(9), l([s(&amp;quot;food&amp;quot;), s(&amp;quot;goo&amp;quot;)]), s(&amp;quot;new&amp;quot;)] % Correct Visual Prolog&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following example of append shows how to use this domain declaration in a typical list-manipulation program.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;class main&lt;br /&gt;
&lt;br /&gt;
domains&lt;br /&gt;
    llist =&lt;br /&gt;
        l(list);&lt;br /&gt;
        i(integer);&lt;br /&gt;
        c(char);&lt;br /&gt;
        s(string).&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    test : ().&lt;br /&gt;
&lt;br /&gt;
end class&lt;br /&gt;
&lt;br /&gt;
implement main&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    append : (A*, A*, A* [out]).&lt;br /&gt;
clauses&lt;br /&gt;
    append([], L, L).&lt;br /&gt;
    append([X | L1], L2, [X | L3]) :-&lt;br /&gt;
        append(L1, L2, L3).&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    test() :-&lt;br /&gt;
        append([s(&amp;quot;likes&amp;quot;), l([s(&amp;quot;bill&amp;quot;), s(&amp;quot;mary&amp;quot;)])], [s(&amp;quot;bill&amp;quot;), s(&amp;quot;sue&amp;quot;)], Ans),&lt;br /&gt;
        stdio::write(&amp;quot;FIRST LIST: &amp;quot;, Ans, &amp;quot;\n\n&amp;quot;),&lt;br /&gt;
        append([l([s(&amp;quot;This&amp;quot;), s(&amp;quot;is&amp;quot;), s(&amp;quot;a&amp;quot;), s(&amp;quot;list&amp;quot;)]), s(&amp;quot;bee&amp;quot;)], [c(&amp;#039;c&amp;#039;)], Ans2),&lt;br /&gt;
        stdio::write(&amp;quot;SECOND LIST: &amp;quot;, Ans2, &amp;quot;\n\n&amp;quot;).&lt;br /&gt;
&lt;br /&gt;
end implement main&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Parsing by Difference Lists ==&lt;br /&gt;
&lt;br /&gt;
The ch07e10.pro program demonstrates [[wikipedia:parsing|parsing]] by &amp;#039;&amp;#039;difference lists&amp;#039;&amp;#039;. The process of parsing by difference lists works by reducing the problem; in this example we transform a string of input into a Prolog structure that can be used or evaluated later.&lt;br /&gt;
&lt;br /&gt;
The parser in this example is for a very primitive computer language. Although this example is very advanced for this point in the tutorial, we decided to put it here because parsing is one of the areas where Visual Prolog is very powerful. If you do not feel ready for this topic, you can skip this example and continue reading the tutorial without any loss of continuity.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;/*******************************************&lt;br /&gt;
* Lexer&lt;br /&gt;
*******************************************/&lt;br /&gt;
&lt;br /&gt;
class lexer&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    tokl : (string Input) -&amp;gt; string* TokenTL.&lt;br /&gt;
&lt;br /&gt;
end class lexer&lt;br /&gt;
&lt;br /&gt;
implement lexer&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    tokl(Input) = [Tok | tokl(Rest)] :-&lt;br /&gt;
        string::fronttoken(Input, Tok, Rest),&lt;br /&gt;
        !.&lt;br /&gt;
    tokl(_) = [].&lt;br /&gt;
&lt;br /&gt;
end implement lexer&lt;br /&gt;
&lt;br /&gt;
/*******************************************&lt;br /&gt;
* Parser&lt;br /&gt;
*******************************************/&lt;br /&gt;
&lt;br /&gt;
class parser&lt;br /&gt;
&lt;br /&gt;
domains&lt;br /&gt;
    program = statement*.&lt;br /&gt;
&lt;br /&gt;
domains&lt;br /&gt;
    statement =&lt;br /&gt;
        if_Then_Else(expression Condition, statement ThenPart, statement ElsePart);&lt;br /&gt;
        if_Then(expression Condition, statement ThenPart);&lt;br /&gt;
        while(expression Condition, statement Body);&lt;br /&gt;
        assign(id Variable, expression Expression).&lt;br /&gt;
&lt;br /&gt;
domains&lt;br /&gt;
    expression =&lt;br /&gt;
        plus(expression, expression);&lt;br /&gt;
        minus(expression, expression);&lt;br /&gt;
        var(id);&lt;br /&gt;
        int(integer).&lt;br /&gt;
&lt;br /&gt;
domains&lt;br /&gt;
    id = string.&lt;br /&gt;
&lt;br /&gt;
predicates&lt;br /&gt;
    program : (string* TL) -&amp;gt; program ProgramTree determ.&lt;br /&gt;
&lt;br /&gt;
end class&lt;br /&gt;
&lt;br /&gt;
implement parser&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    program(TL) = Prog :-&lt;br /&gt;
        Prog = statement_list(TL, TL0),&lt;br /&gt;
        [] = TL0.&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    statement_list : (string* TL1, string* TL0 [out]) -&amp;gt; program Program determ.&lt;br /&gt;
clauses&lt;br /&gt;
    statement_list([], []) = [] :-&lt;br /&gt;
        !.&lt;br /&gt;
    statement_list(TL1, TL0) = [Statement | Program] :-&lt;br /&gt;
        Statement = statement(TL1, TL2),&lt;br /&gt;
        TL2 = [&amp;quot;;&amp;quot; | TL3],&lt;br /&gt;
        Program = statement_list(TL3, TL0).&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    statement : (string* TL1, string* TL0 [out]) -&amp;gt; statement Statement determ.&lt;br /&gt;
clauses&lt;br /&gt;
    statement([&amp;quot;if&amp;quot; | TL1], TL0) = if_then_else(Condition, ThenPart, ElsePart) :-&lt;br /&gt;
        Condition = expression(TL1, TL2),&lt;br /&gt;
        TL2 = [&amp;quot;then&amp;quot; | TL3],&lt;br /&gt;
        ThenPart = statement(TL3, TL4),&lt;br /&gt;
        TL4 = [&amp;quot;else&amp;quot; | TL5],&lt;br /&gt;
        !,&lt;br /&gt;
        ElsePart = statement(TL5, TL6),&lt;br /&gt;
        TL6 = [&amp;quot;fi&amp;quot; | TL0].&lt;br /&gt;
&lt;br /&gt;
    statement([&amp;quot;if&amp;quot; | TL1], TL0) = if_then(Condition, Statement) :-&lt;br /&gt;
        !,&lt;br /&gt;
        Condition = expression(TL1, TL2),&lt;br /&gt;
        TL2 = [&amp;quot;then&amp;quot; | TL3],&lt;br /&gt;
        Statement = statement(TL3, TL4),&lt;br /&gt;
        TL4 = [&amp;quot;fi&amp;quot; | TL0].&lt;br /&gt;
&lt;br /&gt;
    statement([&amp;quot;do&amp;quot; | TL1], TL0) = while(Condition, Statement) :-&lt;br /&gt;
        !,&lt;br /&gt;
        Statement = statement(TL1, TL2),&lt;br /&gt;
        TL2 = [&amp;quot;while&amp;quot; | TL3],&lt;br /&gt;
        Condition = expression(TL3, TL0).&lt;br /&gt;
&lt;br /&gt;
    statement([ID | TL1], TL0) = assign(Id, Exp) :-&lt;br /&gt;
        string::isname(ID),&lt;br /&gt;
        TL1 = [&amp;quot;=&amp;quot; | TL2],&lt;br /&gt;
        Exp = expression(TL2, TL0).&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    expression : (string* TL1, string* TL0 [out]) -&amp;gt; expression Expression determ.&lt;br /&gt;
clauses&lt;br /&gt;
    expression(TL1, TL0) = Exp :-&lt;br /&gt;
        PreTerm = term(TL1, TL2),&lt;br /&gt;
        Exp = termTail(TL2, TL0, PreTerm).&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    termTail : (string* TL1, string* TL0 [out], expression PreExpr) -&amp;gt; expression Expr determ.&lt;br /&gt;
clauses&lt;br /&gt;
    termTail([&amp;quot;+&amp;quot; | TL1], TL0, Exp1) = Exp :-&lt;br /&gt;
        !,&lt;br /&gt;
        Exp2 = term(TL1, TL2),&lt;br /&gt;
        Exp = termTail(TL2, TL0, plus(Exp1, Exp2)).&lt;br /&gt;
&lt;br /&gt;
    termTail([&amp;quot;-&amp;quot; | TL1], TL0, Exp1) = Exp :-&lt;br /&gt;
        !,&lt;br /&gt;
        Exp2 = term(TL1, TL2),&lt;br /&gt;
        Exp = termTail(TL2, TL0, minus(Exp1, Exp2)).&lt;br /&gt;
&lt;br /&gt;
    termTail(TL, TL, Exp) = Exp.&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    term : (string* TL1, string* TL0 [out]) -&amp;gt; expression Expression determ.&lt;br /&gt;
clauses&lt;br /&gt;
    term([Int | Rest], Rest) = int(I) :-&lt;br /&gt;
        try&lt;br /&gt;
            I = toTerm(Int)&lt;br /&gt;
        catch _ do&lt;br /&gt;
            fail&lt;br /&gt;
        end try,&lt;br /&gt;
        !.&lt;br /&gt;
&lt;br /&gt;
    term([Id | Rest], Rest) = var(Id) :-&lt;br /&gt;
        string::isName(Id).&lt;br /&gt;
&lt;br /&gt;
end implement parser&lt;br /&gt;
&lt;br /&gt;
goal&lt;br /&gt;
    console::init(),&lt;br /&gt;
    TokenTL = lexer::tokl(&amp;quot;b=2; if b then a=1 else a=2 fi; do a=a-1 while a;&amp;quot;),&lt;br /&gt;
    if ProgramTree = parser::program(TokenTL) then&lt;br /&gt;
        foreach Stmt in ProgramTree do&lt;br /&gt;
            stdio::write(Stmt, &amp;quot;\n&amp;quot;)&lt;br /&gt;
        end foreach&lt;br /&gt;
    else&lt;br /&gt;
        stdio::write(&amp;quot;Parse error\n&amp;quot;)&lt;br /&gt;
    end if.&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The program will write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;assign(&amp;quot;b&amp;quot;,int(2))&lt;br /&gt;
if_then_else(var(&amp;quot;b&amp;quot;),assign(&amp;quot;a&amp;quot;,int(1)),assign(&amp;quot;a&amp;quot;,int(2)))&lt;br /&gt;
while(var(&amp;quot;a&amp;quot;),assign(&amp;quot;a&amp;quot;,minus(var(&amp;quot;a&amp;quot;),int(1))))&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The transformation in this example is divided into two stages: scanning and parsing. The tokl predicate is the scanner; it accepts a string and converts it into a list of tokens. In this example the input text is a Pascal-like program made up of Pascal-like statements. This programming language only understands certain statements: IF THEN ELSE, IF THEN, DO WHILE, and ASSIGNMENT. Statements are made up of expressions and other statements. Expressions are addition, subtraction, variables, and integers.&lt;br /&gt;
&lt;br /&gt;
Here&amp;#039;s how this example works:&lt;br /&gt;
&lt;br /&gt;
*The &amp;#039;&amp;#039;&amp;#039;program&amp;#039;&amp;#039;&amp;#039; predicate takes a list of tokens call the &amp;#039;&amp;#039;&amp;#039;statement_list&amp;#039;&amp;#039;&amp;#039; predicate on that list.  And then is test that all tokens was used in the parse process.&lt;br /&gt;
*The predicate &amp;#039;&amp;#039;&amp;#039;statement_list&amp;#039;&amp;#039;&amp;#039; takes a list of tokens and tests if the tokens can be divided up into individual statements, each ending with a semicolon.&lt;br /&gt;
*The predicate &amp;#039;&amp;#039;&amp;#039;statement&amp;#039;&amp;#039;&amp;#039; tests if the first tokens of the token list make up a legal statement. If so, the statement is returned in a structure and the remaining tokens are returned back to &amp;#039;&amp;#039;&amp;#039;statement_list&amp;#039;&amp;#039;&amp;#039;.&lt;br /&gt;
*The four clauses of the &amp;#039;&amp;#039;&amp;#039;statement&amp;#039;&amp;#039;&amp;#039; correspond to the four types of statements the parser understands.&lt;br /&gt;
**If the first &amp;#039;&amp;#039;&amp;#039;statement&amp;#039;&amp;#039;&amp;#039; clause is unable to transform the list of tokens into an &amp;#039;&amp;#039;IF THEN ELSE&amp;#039;&amp;#039; statement, the clause fails and backtracks to the next &amp;#039;&amp;#039;&amp;#039;statement&amp;#039;&amp;#039;&amp;#039; clause.&lt;br /&gt;
**The second clause tries to transform the list of tokens into an &amp;#039;&amp;#039;IF THEN&amp;#039;&amp;#039; statement.&lt;br /&gt;
**If that clause fails, the next clause tries to transform the list of tokens into a &amp;#039;&amp;#039;DO WHILE&amp;#039;&amp;#039; statement.&lt;br /&gt;
**And if all the first three &amp;#039;&amp;#039;&amp;#039;statement&amp;#039;&amp;#039;&amp;#039; clauses fail, the last clause for that predicate tests if the statement does assignment. This clause tests for assignment by testing if the first term is a symbol, the second term is &amp;quot;=&amp;quot;, and the next terms make up a simple math expression.&lt;br /&gt;
*The &amp;#039;&amp;#039;&amp;#039;expression&amp;#039;&amp;#039;&amp;#039;, &amp;#039;&amp;#039;&amp;#039;term&amp;#039;&amp;#039;&amp;#039;, and &amp;#039;&amp;#039;&amp;#039;termTail&amp;#039;&amp;#039;&amp;#039; predicates work in simailar ways, by testing if the first terms are expressions and – if so – returning the remainder of the terms and an expression structure back to &amp;#039;&amp;#039;&amp;#039;statement&amp;#039;&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
==Summary==&lt;br /&gt;
&lt;br /&gt;
These are the important points covered in this tutorial:&lt;br /&gt;
&lt;br /&gt;
*&amp;#039;&amp;#039;Lists&amp;#039;&amp;#039; can contain an arbitrary number of elements; you declare them by adding an asterisk at the end of a previously defined domain.&lt;br /&gt;
&lt;br /&gt;
*A list is a recursive compound object that consists of a head and a tail. The head is the first element and the tail is the rest of the list (without the first element). The tail of a list is always a list; the head of a list is an element. A list can contain zero or more elements; the empty list is written [].&lt;br /&gt;
&lt;br /&gt;
*The elements in a list can be anything, including other lists; all elements in a list must belong to the same domain. The domain declaration for the elements must be of this form:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;domains&lt;br /&gt;
   element_list = elements*.&lt;br /&gt;
   elements = ....&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
where elements = one of the standard domains (integer, real, etc.) or a set of alternatives marked with different functors (int(integer); rl(real); smb(symbol); etc.). You can only mix types in a list in Visual Prolog by enclosing them in compound objects/functors.&lt;br /&gt;
&lt;br /&gt;
*You can use separators (commas, [, and |) to make the head and tail of a list explicit; for example, the list&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;[a, b, c, d]&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
can be written as:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;[a | [b, c, d]] or&lt;br /&gt;
[a, b | [c, d]] or&lt;br /&gt;
[a, b, c | [d]] or&lt;br /&gt;
[a | [b | [c, d]]] or&lt;br /&gt;
[a | [b | [c | [d]]]] or&lt;br /&gt;
[a | [b | [c | [d | []]]]]&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*List processing consists of recursively removing the head of the list (and usually doing something with it) until the list is an empty list.&lt;br /&gt;
&lt;br /&gt;
*The list predicates can be found in the &amp;#039;&amp;#039;&amp;#039;list&amp;#039;&amp;#039;&amp;#039; class.&lt;br /&gt;
&lt;br /&gt;
*Visual Prolog provides a built-in construction,  list comprehension, which takes a goal as one of its arguments and collects all of the solutions to that goal into a single list. It has the syntax&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;Result = [Argument || myPredicate(Argument)]&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Because Visual Prolog requires that all elements in a list belong to the same domain, you use functors to create a list that stores different types of elements.&lt;br /&gt;
&lt;br /&gt;
*The process of &amp;#039;&amp;#039;parsing by difference lists&amp;#039;&amp;#039; works by reducing the problem; the example in this tutorial transforms a string of input into a Prolog structure that can be used or evaluated later.&lt;br /&gt;
&lt;br /&gt;
[[ru:Списки и рекурсия]]&lt;br /&gt;
[[Category:Data types and handling]]&lt;/div&gt;</summary>
		<author><name>Kasper B H Petersen</name></author>
	</entry>
	<entry>
		<id>https://wiki.visual-prolog.com/index.php?title=File:FundamentalVisualPrologBusiness_fig6.png&amp;diff=4834</id>
		<title>File:FundamentalVisualPrologBusiness fig6.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.visual-prolog.com/index.php?title=File:FundamentalVisualPrologBusiness_fig6.png&amp;diff=4834"/>
		<updated>2021-10-08T06:59:32Z</updated>

		<summary type="html">&lt;p&gt;Kasper B H Petersen: Kasper B H Petersen reverted File:FundamentalVisualPrologBusiness fig6.png to an old version&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Fundamental Visual Prolog - Business 06&lt;br /&gt;
&lt;br /&gt;
{{Tutorial Image}}&lt;/div&gt;</summary>
		<author><name>Kasper B H Petersen</name></author>
	</entry>
	<entry>
		<id>https://wiki.visual-prolog.com/index.php?title=File:FundamentalVisualPrologBusiness_fig6.png&amp;diff=4833</id>
		<title>File:FundamentalVisualPrologBusiness fig6.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.visual-prolog.com/index.php?title=File:FundamentalVisualPrologBusiness_fig6.png&amp;diff=4833"/>
		<updated>2021-10-08T06:57:00Z</updated>

		<summary type="html">&lt;p&gt;Kasper B H Petersen: Kasper B H Petersen uploaded a new version of File:FundamentalVisualPrologBusiness fig6.png&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Fundamental Visual Prolog - Business 06&lt;br /&gt;
&lt;br /&gt;
{{Tutorial Image}}&lt;/div&gt;</summary>
		<author><name>Kasper B H Petersen</name></author>
	</entry>
	<entry>
		<id>https://wiki.visual-prolog.com/index.php?title=Fundamental_Visual_Prolog_-_GUI&amp;diff=4832</id>
		<title>Fundamental Visual Prolog - GUI</title>
		<link rel="alternate" type="text/html" href="https://wiki.visual-prolog.com/index.php?title=Fundamental_Visual_Prolog_-_GUI&amp;diff=4832"/>
		<updated>2021-10-07T11:38:33Z</updated>

		<summary type="html">&lt;p&gt;Kasper B H Petersen: /* Understanding What we have Done So Far */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{FundamentalPrologNavbar}}&lt;br /&gt;
&lt;br /&gt;
In this tutorial, we shall add a simple [[wikipedia:Graphical_User_Interface|Graphical User Interface]] (GUI) front end to the family project, which was developed in an earlier tutorial. We shall learn to do create and edit most of the GUI components of a simple Windows program directly within the Visual Prolog IDE (Integrated Development Environment). We shall learn a bit about handling of GUI events (like clicking a button on a specific part of the GUI, etc.), and how they work within a Visual Prolog program. We shall also learn about modal dialogs with two examples: one, which is inbuilt by the Windows operating system, and one, which we shall build for ourselves for our program.&lt;br /&gt;
&lt;br /&gt;
The source files of the example project used in this tutorial are part of the installable examples (in the IDE: &amp;#039;&amp;#039;&amp;#039;Help -&amp;gt; Install Examples...&amp;#039;&amp;#039;&amp;#039;).&lt;br /&gt;
&lt;br /&gt;
==Introduction to a GUI==&lt;br /&gt;
&lt;br /&gt;
A GUI is simply an acronym for Graphical User Interface. In the Windows operating system environment the term represents the familiar windows with the menu bar, toolbar, the little buttons on the top right hand corner of a window, etc. Each of those elements is known as a GUI component, and in well designed programs, these components work as per conventionally accepted norms.&lt;br /&gt;
&lt;br /&gt;
In programming terms, a GUI does two things. It uses complex graphical routines to put (and restore) graphical images on the relevant parts of the computer monitor. (E.g. the little square with an X on it on the top right corner of a window). It also controls the behaviour of the mouse and other input devices over these graphical areas. Mercifully, both these detailed programming are done by the operating system. As a programmer one need not get down on our knees to program such graphic, mouse and keyboard functions. Windows does it for us. It has given an API (Application Programming Interface) which can be used to setup the GUI required for any program.&lt;br /&gt;
&lt;br /&gt;
Furthermore, Visual Prolog has added one more layer - the PFC (Prolog Foundation Classes) to help out not only with the GUI but with other areas of programming too.&lt;br /&gt;
&lt;br /&gt;
And even more; the Visual Prolog IDE can be used to visually create the mock-ups of the final GUI that would be used by the program that you would be developing. In this tutorial we shall set out to do just that. We will be using the logic of the family example that was tackled in a previous tutorial.&lt;br /&gt;
&lt;br /&gt;
There is a lot of difference between a GUI and console programs. Though both console programs and GUI programs always starts at a fixed entry point (from the &amp;#039;&amp;#039;Goal&amp;#039;&amp;#039; procedure), that is where the similarity ends. Console programs do not show graphical elements, so they have the user input either from start-up parameters or from direct questions setup by the programmer in advance. The sequence and direction of activities in the program would have to be determined by the programmer. The user cannot modify that sequence. In a console program, the program is started from the &amp;#039;&amp;#039;Goal&amp;#039;&amp;#039; procedure and it is then worked logically from that point onwards, straitjacketing the user through a series of logical steps set out by the programmer.&lt;br /&gt;
&lt;br /&gt;
With GUI programs, the programmer can choose to be flexible. The user can be given options what should be done on which part of the program. For example; if you start any conventional Windows program, it normally will not press you to do this or do that. You can laze around casually flipping through the menus without really clicking on any of them. Consider this scenario: The File menu will have several menu items. You can take the mouse cursor through each one of them without really being compelled to click on any of the menu item you may find there. In fact, one of the common methods by which people get to grips with a piece of software is by such casual browsing over the GUI of a program.&lt;br /&gt;
&lt;br /&gt;
Anyway, to cut a long story short; the programmer has to use a different strategy when programming GUI programs. On one hand, the programming is easier because there is no rigidity or regimentation in the activities of the program that will be carried out.&lt;br /&gt;
&lt;br /&gt;
But on the other hand, the programmer needs to know how each of the GUI components works, what are conventionally accepted practices and how to adhere to those practices so that the user is not given unnecessary surprises when using the program. Also, sometimes it would be difficult to predict the consequences that may follow due to some GUI event being triggered. Hence the programmer has to carefully isolate the logic so that it remains valid irrespective of how the GUI was used, and carefully accommodate those situations, where the program&amp;#039;s logic may be unable to accommodate (using polite, easy to understand warning dialogs, etc.).&lt;br /&gt;
&lt;br /&gt;
==GUI: Responding to Events==&lt;br /&gt;
&lt;br /&gt;
In a GUI program, all the GUI components wait for inputs from the keyboard and/or mouse (and/or other pointing devices such as digitizer puck, etc.).&lt;br /&gt;
&lt;br /&gt;
The information from such input devices (click of a mouse and other such GUI activity) is known as an &amp;#039;&amp;#039;event&amp;#039;&amp;#039;. There are other &amp;#039;&amp;#039;events&amp;#039;&amp;#039; to which a GUI responds - some of them are internally generated by the operating system such as ticking of the internal clock, interaction with other programs running concurrently, ActiveX events, etc. Depending on what the program is expected to do, the programmer earmarks appropriate portions of code to respond to relevant &amp;#039;&amp;#039;events&amp;#039;&amp;#039;. PFC GUI package provides the set of listeners and responders to handle GUI events.&lt;br /&gt;
&lt;br /&gt;
When the program responds to an event, the program can either &amp;#039;&amp;#039;listen&amp;#039;&amp;#039; the event or &amp;#039;&amp;#039;handle&amp;#039;&amp;#039; the event. If an &amp;#039;&amp;#039;event&amp;#039;&amp;#039; is listened, then it means the program can just do something. For example the &amp;#039;&amp;#039;show event&amp;#039;&amp;#039; comes, when a window is shown, hence program can make some initialization here. If an &amp;#039;&amp;#039;event&amp;#039;&amp;#039; is responded, then it means the program can change the behaviour of the system. For example, on the &amp;#039;&amp;#039;close event&amp;#039;&amp;#039; the program can respond either to close window or to keep it open.&lt;br /&gt;
&lt;br /&gt;
Please notice also that the GUI program actually does nothing but waits till a GUI event is invoked.&lt;br /&gt;
&lt;br /&gt;
One important feature of event handling must be understood here:&lt;br /&gt;
&lt;br /&gt;
Because the code of a listener and a responder wait till an event has happened; it may seem as if there is no obvious logic to it. Other modules need not even know what is happening privately within the class which was actually handling a GUI event. In our earlier tutorial, we noticed that all the logic was well contained and logically connected to one another. But in case of GUI programs, parts of the code (the one that handles GUI events) would be &amp;#039;&amp;#039;fragmented&amp;#039;&amp;#039; and placed under different listeners and responders.&lt;br /&gt;
&lt;br /&gt;
In this tutorial, we shall go about taking the same logic of the family example which was dealt in an earlier tutorial, and then use that logic via a GUI interface.&lt;br /&gt;
&lt;br /&gt;
==Starting a GUI Project==&lt;br /&gt;
&lt;br /&gt;
Let us start at the very beginning (a very good place to start!). When we create the project in the Visual Prolog IDE, make sure that the &amp;#039;&amp;#039;&amp;#039;Project Kind&amp;#039;&amp;#039;&amp;#039; is set to &amp;#039;&amp;#039;&amp;#039;GUI application&amp;#039;&amp;#039;&amp;#039; in &amp;#039;&amp;#039;&amp;#039;MDI mode&amp;#039;&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
The IDE then creates the initial set of modules required to handle the GUI along with the GUI component resources: the main menu, one top toolbar, one bottom status bar, the About dialog and the main Task Window of the program.&lt;br /&gt;
&lt;br /&gt;
Just after you create a project in this fashion, you can immediately compile it to get an empty GUI program. At this stage, the program actually would not do anything. However, it will have all the basic functionality expected in a GUI program. Visual Prolog has simply constructed the essential skeleton of a working GUI program and has provided some features commonly required.&lt;br /&gt;
&lt;br /&gt;
For example; within the main window (known here as the Task Window) of the application Visual Prolog gives another window titled Messages. This window is used internally to act as the &amp;#039;&amp;#039;console&amp;#039;&amp;#039;. When the programmer uses the stdio::write(...) predicate in the program, the output would get directed to this Messages window. If Visual Prolog has not redirected the output of PFC class stdio to the Messages window, those strings would not be seen, as a GUI environment does not have a console area by default.&lt;br /&gt;
&lt;br /&gt;
In a console application, the console is always available as a &amp;#039;&amp;#039;blackboard&amp;#039;&amp;#039; onto which the programmer can deposit output. That is why those applications are known as &amp;#039;&amp;#039;console&amp;#039;&amp;#039; applications. We saw that in an earlier tutorial that we could simply write to the &amp;#039;&amp;#039;console&amp;#039;&amp;#039; in such an application using stdio::write(...) predicate.&lt;br /&gt;
&lt;br /&gt;
When you run our compiled GUI program at this stage, you would notice that you can flip through the menus, re-size the outer main window (or Task Window&amp;#039;&amp;#039;)&amp;#039;&amp;#039; of the program, double click on the Messages window to zoom it full extents within the Task Window, etc. Visual Prolog even gives a small pop-up menu for the Messages window which is often convenient. Right click anywhere inside the Messages window, and a small menu would open up with which you can clear the contents of the Messages window and do other activities.&lt;br /&gt;
&lt;br /&gt;
But at this point this simple GUI program does not have any logical functionality that we desire. We need to do some further work to achieve this functionality.&lt;br /&gt;
&lt;br /&gt;
Before we embark on populating the project with the actual working logic of the program, we shall create and/or modify some GUI components that we need. Under normal circumstances, it is here where the programmer would have to spend some time thinking out a strategy for the GUI of the program. A clear list of GUI components would have to be made, and only then one should embark on the creation and/or modification of the components. This activity should not be carried out in an unplanned manner. But for the sake of simplicity, we shall proceed in this tutorial with the assumption that this planning process is over.&lt;br /&gt;
&lt;br /&gt;
All GUI components are stored as separate resource files during the coding phase. In most other programming languages; these resource files are separately compiled and then included into the main code during the linking process. Visual Prolog deals with all this resource compilation and linkage issues automatically without unnecessarily bothering the user.&lt;br /&gt;
&lt;br /&gt;
==Creating a Modal Dialog==&lt;br /&gt;
&lt;br /&gt;
Now we shall add another GUI component that we would need later on in our program. It is a dialog box which will be used to feed the name of a person to the program for the program to process. In the Project tree (where all the modules and resources are listed in a clearly laid out tree menu), right click on the Task Window and from the context menu, select New in New Package...&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui02.PNG]]&lt;br /&gt;
&lt;br /&gt;
The Create Project Item dialog would be presented. Ensure that Dialog is selected from the left hand side and on the right hand side enter the &amp;#039;&amp;#039;&amp;#039;ancestorDialog&amp;#039;&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui03.PNG]]&lt;br /&gt;
&lt;br /&gt;
A default dialog is created for you to edit. As we will not be implementing a Help function for this dialog, we will click on that particular GUI component (i.e. the Help button) and we shall delete that by pressing the DEL key.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui04.PNG]]&lt;br /&gt;
&lt;br /&gt;
Then the other two buttons should be selected and should be shifted about on the dialog box in order to make the dialog look presentable. The final result would look something as shown below:&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui05.png]]&lt;br /&gt;
&lt;br /&gt;
Using the dialog editing controls, we shall now insert a static text. (The word &amp;#039;&amp;#039;static&amp;#039;&amp;#039; implies a non-clickable GUI element). Refer the previous image. On clicking the static text creation button, we can mark out the rectangular area, where our text would appear as seen below:&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui06.png]]&lt;br /&gt;
&lt;br /&gt;
On releasing the mouse you will see the control on the dialog. Left click on the just created control and the properties panel would show the properties of the created control. Under the Text field, write &amp;quot;Person&amp;quot;: as seen below. That would be the text which would appear inside the dialog.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui07.png]]&lt;br /&gt;
&lt;br /&gt;
In a similar fashion, we shall use the dialog editing controls to insert an editable text field or an edit control, as seen below:&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui08.png]]&lt;br /&gt;
&lt;br /&gt;
This time, we shall leave the text field empty and instead change the name to something meaningful (instead of the default name which is given by the IDE) as seen below. This name is used within the program code to refer to this edit field in the program&amp;#039;s code as fact variable.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui09.png]]&lt;br /&gt;
&lt;br /&gt;
This is how finally our dialog would look like:&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui24.png]]&lt;br /&gt;
&lt;br /&gt;
We have one last step which is needed to be performed. Each dialog has a property known as a &amp;#039;&amp;#039;Visit Order&amp;#039;&amp;#039;. That is the order by which the controls (i.e. GUI components that interact with the user) on that dialog are visited, when the user clicks on the TAB key. The phrase &amp;quot;&amp;#039;&amp;#039;visit a control&amp;#039;&amp;#039;&amp;quot; means that the said control receives the &amp;#039;&amp;#039;input focus&amp;#039;&amp;#039;. (But then that is more jargon!) The phrase &amp;#039;&amp;#039;the control receiving the input focus&amp;#039;&amp;#039;, means the said control which is immediately receptive to inputs from the keyboard. For example; if the edit field had the input focus one would see the blinking caret within the field ready to accept characters entered through the keyboard.&lt;br /&gt;
&lt;br /&gt;
In order to change the visit order, right click on the dialog, and click on Visit Order in the context menu that opens up.&lt;br /&gt;
&lt;br /&gt;
Small buttons will appear on some of the GUI components of the dialog box as shown in the figure below. As seen here, the text edit control (&amp;#039;&amp;#039;idc_ancestordialog_personname&amp;#039;&amp;#039;) has a visit order of 3 whereas the visit order number for the OK button is 1.&lt;br /&gt;
&lt;br /&gt;
This means that when the dialog is presented to the user, the text edit will not be the one which will receive keyboard characters immediately. When the user presses the TAB button, then the focus will shift to the Cancel button, and only on pressing the TAB button one more time would the focus will go to the edit control. Only then the text edit control would receive keyboard input.&lt;br /&gt;
&lt;br /&gt;
In short, the edit field can be said to have the last &amp;#039;&amp;#039;visit order&amp;#039;&amp;#039; number, with respect to all the controls in the dialog.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui25.png]]&lt;br /&gt;
&lt;br /&gt;
We need to change this. Click on the small button labeled 3. This will open up the Visit Order dialog box as shown above. You can change the order using the &amp;#039;&amp;#039;+&amp;#039;&amp;#039; and &amp;#039;&amp;#039;-&amp;#039;&amp;#039; buttons. In our case, we will use the change the visit order so that &amp;#039;&amp;#039;idc_ancestordialog_personname&amp;#039;&amp;#039; has a visit order of 1. Now, when the dialog gets used in the program; the input focus will first be on the edit control.&lt;br /&gt;
&lt;br /&gt;
Please note that in dialogs, there is another property called the &amp;#039;&amp;#039;default push button&amp;#039;&amp;#039; which can be set separately from the visit order. An event for the button that has been set to be the &amp;#039;&amp;#039;default push button&amp;#039;&amp;#039; will be triggered on pressing the ENTER key irrespective of which control had the &amp;#039;&amp;#039;input focus&amp;#039;&amp;#039;. Usually, the default push button is set to be the OK button.&lt;br /&gt;
&lt;br /&gt;
When you right-click on the dialog, you can set the overall dialog attributes using the following dialog. If you notice, the Type of the dialog is set to Modal. The term &amp;#039;&amp;#039;modal&amp;#039;&amp;#039; reflects the fact that whenever the dialog is presented to the user, the GUI would stop responding to other parts of the program, when the dialog is visible. Only when the dialog is disposed off by the user (by pressing the OK or Cancel button) the GUI will become responsive once again to all GUI activity.&lt;br /&gt;
&lt;br /&gt;
When you click on the dialog, you can set the overall dialog properties on the properties panel. If you notice, the Type of the dialog is set to Modal. The term modal reflects the fact that whenever the dialog is presented to the user, the GUI would stop responding to other parts of the program, when the dialog is visible. Only when the dialog is disposed off by the user (by pressing the OK or Cancel button) the GUI will become responsive once again to all GUI activity.&lt;br /&gt;
&lt;br /&gt;
A &amp;#039;&amp;#039;modeless&amp;#039;&amp;#039; dialog on the other hand does not make this restriction. The entire GUI interface is responsive even if the dialog is active. Programming a &amp;#039;&amp;#039;modeless&amp;#039;&amp;#039; dialog requires a little bit more thought and it is not touched upon in this tutorial.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui30.png]]&lt;br /&gt;
&lt;br /&gt;
Using the same Dialog Attributes (see figure above), you should also change the title to the &amp;quot;Ancestor of ...&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
==Modifying the Menu==&lt;br /&gt;
&lt;br /&gt;
Now we shall modify the main menu of the program. As noted before, the IDE would have provided a default menu consisting of some standard menu items which are found in many programs. We need to edit that menu to suit our program&amp;#039;s functionality. Using the project tree, right click on the TaskMenu.mnu item as seen below:&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui10.png]]&lt;br /&gt;
&lt;br /&gt;
This will start the Menu Editor. The main dialog of the Editor is seen below. Click on the Edit button after ensuring that the TaskMenu.mnu is selected in the project window.&lt;br /&gt;
&lt;br /&gt;
This will open up the following Menu Item Attributes dialog, as shown above. We will change the name from &amp;#039;&amp;#039;&amp;amp;amp;Edit&amp;#039;&amp;#039; to &amp;#039;&amp;#039;&amp;amp;amp;Query&amp;#039;&amp;#039;. The ampersand sign (&amp;amp;amp;) before Q indicates the letter which would get underlined in the menu. Users can use that alphabet to quickly access the menu.&lt;br /&gt;
&lt;br /&gt;
You can test this feature by clicking on the Test button in the above dialog. The top menu of the IDE will be temporarily replaced by the menu you are designing. You can then browse the menu just to get a feel of it. You can open it submenus, etc. To exit the test mode, you can click somewhere in the IDE window out of the tested menu.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui12.png]]&lt;br /&gt;
&lt;br /&gt;
We shall now return back to the main TaskMenu dialog. Double click on the &amp;#039;&amp;#039;&amp;amp;amp;Query&amp;#039;&amp;#039; entry, and you would notice that it still contains the menu items of the old Edit menu (Undo, Redo, Cut, Copy and Paste). Delete all the menu items you see within for that main menu entry (&amp;amp;amp;Query). Also change the Constant Prefix setting to &amp;#039;&amp;#039;id_query&amp;#039;&amp;#039;. The constant prefix is used internally by the IDE to construct the constants that would represent the various menu items. Those constants would be used internally in the code to refer to the menu items.&lt;br /&gt;
&lt;br /&gt;
Now we shall add some menu items under the main Query menu item. To do that, click on the New &amp;#039;&amp;#039;&amp;#039;SubItem&amp;#039;&amp;#039;&amp;#039; item and enter the information you see in the following figure:&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui14.png]]&lt;br /&gt;
&lt;br /&gt;
You would note that the Constant is automatically created for you depending on the text you enter for the menu item. In the above example it would be &amp;#039;&amp;#039;id_query_father&amp;#039;&amp;#039; as seen in the previous figure. In a similar fashion, create menu entries for &amp;amp;amp;Grandfather and &amp;amp;amp;Ancestor of ...&lt;br /&gt;
&lt;br /&gt;
Note that by convention an ellipsis (three dots) is used at the end of those menu items which will yield another dialog before any work is carried out. In the above example, &amp;amp;amp;Father and &amp;amp;amp;Grandfather menu items will not have the ellipsis. But the &amp;amp;amp;Ancestor of ... entry will have the ellipsis, because on invoking that menu item, a dialog would open up before any activity gets done.&lt;br /&gt;
&lt;br /&gt;
One last step is remaining in the editing of the TaskWindow menu. By default, when the IDE creates the menu, the &amp;#039;&amp;#039;&amp;#039;File -&amp;gt; Open&amp;#039;&amp;#039;&amp;#039; menu is disabled. You would have to locate that menu item, and enable it by removing the checkmark from that menu item&amp;#039;s Menu Item Attributes dialog, as seen below:&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui16.png]]&lt;br /&gt;
&lt;br /&gt;
By the way, in the previous figure you would note that you can set the accelerator (i.e. the hot-key) which can be invoked by the user to quickly invoke the same function as the menu item. In the above example, it would be the F8 function key. It should also be noted that the menu item for opening a file is indicated here as &amp;amp;amp;Open (without an ellipsis). You should correct that so that it reads &amp;amp;amp;Open ... to suit the ellipsis convention.&lt;br /&gt;
&lt;br /&gt;
When you close the TaskMenu creation dialog, the IDE would confirm whether you want to save the menu. Click on Save.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui15.png]]&lt;br /&gt;
&lt;br /&gt;
==Modifying the Toolbar==&lt;br /&gt;
&lt;br /&gt;
The toolbar of the application is another useful GUI component. Usually, it would contain buttons representing some of the functions of various menu items. In short, those buttons act as short cuts to the menu. We shall now go about editing the program&amp;#039;s toolbar. A default toolbar is created for the program by the Visual Prolog IDE when you first create the project. From the Project Tree, double-click on the ProjectToolbar.tb.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui26.png]]&lt;br /&gt;
&lt;br /&gt;
This will invoke the toolbar editor. Note that the top portion represents the toolbar that you are editing and the bottom portion indicates the various controls that are available for you to edit those toolbar components.&lt;br /&gt;
&lt;br /&gt;
In the toolbar, you would notice a set of buttons with predefined iconic images (as commonly accepted in GUI programs) If so desired, you can change those iconic images too but in this tutorial we shall not get into that fine detail. It should be indicated here that the Visual Prolog IDE does contain a nifty little icon editing program right inside it. For larger images, the IDE opens MS Paint for editing.&lt;br /&gt;
&lt;br /&gt;
The buttons have been mapped out to a set of menu-item functions. But as we have now edited the menu items, we shall also edit the toolbar buttons and map it to the correct locations.&lt;br /&gt;
&lt;br /&gt;
Firstly, we need to remove the buttons representing cut, copy and paste as our program does not have those capabilities. Hence select those buttons and delete them from the toolbar. After deletion the toolbar should look as follows:&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui28.png]]&lt;br /&gt;
&lt;br /&gt;
We shall now map the Undo, Redo and the Help buttons to represent the following menu items: &amp;#039;&amp;#039;&amp;#039;Query -&amp;gt; Father...&amp;#039;&amp;#039;&amp;#039;, &amp;#039;&amp;#039;&amp;#039;Query -&amp;gt; Grandfather...&amp;#039;&amp;#039;&amp;#039; and &amp;#039;&amp;#039;&amp;#039;Query -&amp;gt; Ancestor of ...&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
(As noted before, we would not be changing the images of those buttons in this tutorial.)&lt;br /&gt;
&lt;br /&gt;
Double click on the Undo toolbar button and in the Button Attributes dialog that is presented, change the Constant that internally represents the toolbar button from &amp;#039;&amp;#039;id_edit_undo&amp;#039;&amp;#039; to &amp;#039;&amp;#039;id_query_father&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui29.png]]&lt;br /&gt;
&lt;br /&gt;
In the same dialog box, you should change the Status Text from:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;Undo;Undo&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
to&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;Query fathers;List of all fathers listed in the database&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The semicolon in the above string breaks up the string into two parts. The first part is displayed as a tool-tip on the button itself and the second one will appear in the status-line of the main window.&lt;br /&gt;
&lt;br /&gt;
In a similar fashion; change the Redo button&amp;#039;s constant so that it is now having the value of &amp;#039;&amp;#039;id_query_grandfather&amp;#039;&amp;#039;. And the Help button&amp;#039;s constant should get the value of &amp;#039;&amp;#039;id_query_ancestor_of&amp;#039;&amp;#039;. The status-line of these two buttons also should be suitably modified.&lt;br /&gt;
&lt;br /&gt;
==Getting the Main Code into the Program==&lt;br /&gt;
&lt;br /&gt;
We have finished all the work for all the GUI functionality that we need from the program. Now we shall start inserting the logic of the code. Before we do that, let us understand some important differences between the way programming used to be done and how it would now be done for a GUI program.&lt;br /&gt;
&lt;br /&gt;
When a user uses a GUI program, it is like the user is using a room. The user comes into the room through the main door all right but once inside the room; the user is free to decide which part of the room would be put to use. Undoubtedly, the programmer has the last say on how each of those parts would actually work. But by and large the user is free to decide which part of the program to activate. The &amp;#039;&amp;#039;Goal&amp;#039;&amp;#039; procedure is still present in a GUI program but here all it does is to just set up the stage for the user to work on. It is like the main door to the room in our analogy.&lt;br /&gt;
&lt;br /&gt;
What does this imply for the programmer? The logic of the code earlier was contained inside one module. Now it will be spread over several modules, depending on the logic which is controlled by corresponding GUI components.&lt;br /&gt;
&lt;br /&gt;
Let us add some basic logical code that is needed by the program. Open TaskWindow.pro and insert the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;domains&lt;br /&gt;
    gender = female(); male().&lt;br /&gt;
&lt;br /&gt;
class facts - familyDB&lt;br /&gt;
    person : (string Name, gender Gender).&lt;br /&gt;
    parent : (string Person, string Parent).&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    father : (string Person, string Father) nondeterm anyflow.&lt;br /&gt;
clauses&lt;br /&gt;
    father(Person, Father) :-&lt;br /&gt;
        parent(Person, Father),&lt;br /&gt;
        person(Father, male()).&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    grandFather : (string Person, string Grandfather) nondeterm anyflow.&lt;br /&gt;
clauses&lt;br /&gt;
    grandfather(Person, Grandfather) :-&lt;br /&gt;
        parent(Person, Parent),&lt;br /&gt;
        father(Parent, Grandfather).&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    ancestor : (string Person, string Ancestor) nondeterm anyflow.&lt;br /&gt;
clauses&lt;br /&gt;
    ancestor(Person, Ancestor) :-&lt;br /&gt;
        parent(Person, Ancestor).&lt;br /&gt;
    ancestor(Person, Ancestor) :-&lt;br /&gt;
        parent(Person, P1),&lt;br /&gt;
        ancestor(P1, Ancestor).&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    reconsult : (string FileName).&lt;br /&gt;
clauses&lt;br /&gt;
    reconsult(Filename) :-&lt;br /&gt;
        retractFactDB(familyDB),&lt;br /&gt;
        file::consult(Filename, familyDB).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code is the logical core of the program. In this tutorial, we would directly be inserting it into the module TaskWindow.pro because we want you to see how the GUI components reach into the logical core to perform various actions. In more complex examples; the logical core would be residing separately, sometimes spread over several modules. The GUI modules (such as &amp;#039;&amp;#039;TaskWindow&amp;#039;&amp;#039;, etc.) would then be referring it to those modules separately by increasing the &amp;#039;&amp;#039;scope&amp;#039;&amp;#039; of the module (discussed in an earlier tutorial).&lt;br /&gt;
&lt;br /&gt;
Actually, it would be good practice to keep the logical core of the program separate from all GUI related modules as far as possible, but in this tutorial we shall knowingly ignore this sound advice.&lt;br /&gt;
&lt;br /&gt;
==Encapsulating the Interactive Code==&lt;br /&gt;
&lt;br /&gt;
Now that the very core logic has been taken care of, we need to insert the interactive bits. In the Project Tree right click on TaskWindow.win entry. This entry represents the Windows resource for that main TaskWindow. All clicks, menu events, etc. happening within that TaskWindow will have to be handled using event handlers written for that window. On right clicking at that selection, a small context menu would open up as shown below. Select Open from that menu.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui17.png]]&lt;br /&gt;
&lt;br /&gt;
The Dialog and Window Expert (shown below) helps you set default listeners and responders for controls (interactive GUI components) of a particular window or a dialog. The blue filled circle indicates that there is no listener or responder for the indicated control. The green tick-mark indicates that a listener or responder is present.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui18.png]]&lt;br /&gt;
&lt;br /&gt;
Using the above dialog, ensure that an event handler is set for the menu item represented by the constant &amp;#039;&amp;#039;id_file_open&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
Now, in the Project tree click on the TaskWindow.pro module so that it becomes selected, and using the Build menu just compile that module. If the TaskWindow.pro module is not selected then the Compile menu item in the &amp;#039;&amp;#039;Build&amp;#039;&amp;#039; menu would be disabled, so beware!&lt;br /&gt;
&lt;br /&gt;
When Visual Prolog compiles a module, it reorganizes the project tree so that all the pertinent predicates/domains, etc. get laid out cleanly for us to access. Hence, we would be using this feature to ensure that the IDE lists out all the predicates that are declared in the TaskWindow.pro module. We can then navigate to the predicate we want.&lt;br /&gt;
&lt;br /&gt;
Note that the IDE intelligently recognizes that TaskWindow.pro may need some additional modules, and it compiles the module in two passes.&lt;br /&gt;
&lt;br /&gt;
After the compilation is over; when we refer to the TaskWindow predicates, in the project tree you would notice that all the entities are seen:&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui19.png]]&lt;br /&gt;
&lt;br /&gt;
You will find that the Predicates portion of the taskwindow.pro module would reveal the onFileOpen predicate -- which was absent earlier.&lt;br /&gt;
&lt;br /&gt;
When you double-click on that predicate, it will open the editor directly at the location of the clause of the onFileOpen predicate. In case there are multiple clauses, then it would take the cursor to the first clause body.&lt;br /&gt;
&lt;br /&gt;
The onFileOpen predicate is called a &amp;#039;&amp;#039;listener&amp;#039;&amp;#039;. As a programmer you need not call this predicate on your own. Windows will automatically call it when the appropriate GUI component is activated (in this case the menu item is clicked)&lt;br /&gt;
&lt;br /&gt;
By default the following code would have been inserted for this event handler:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;onFileOpen(_Source, _MenuTag).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Replace that code with the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;clauses&lt;br /&gt;
    onFileOpen(_Source, _MenuTag) :-&lt;br /&gt;
         Filename = vpiCommonDialogs::getFileName(&lt;br /&gt;
              &amp;quot;*.txt&amp;quot;, [&amp;quot;Family data files (*.txt)&amp;quot;,&amp;quot;*.txt&amp;quot;,&amp;quot;All files&amp;quot;, &amp;quot;*.*&amp;quot;],&lt;br /&gt;
              &amp;quot;Load family database&amp;quot;,&lt;br /&gt;
               [], &amp;quot;.&amp;quot;, _),&lt;br /&gt;
         ! ,&lt;br /&gt;
         reconsult(Filename),&lt;br /&gt;
         stdIO::writef(&amp;quot;Database % loaded\n&amp;quot;, Filename).&lt;br /&gt;
    onFileOpen(_Source, _MenuTag).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you examine the above code, you would notice that we have simply added a clause body above the one given by the IDE. The first clause body will open up the standard Windows dialog box from where the database can be loaded. The second clause body acts as a fail-safe mechanism in case the person cancels that dialog box.&lt;br /&gt;
&lt;br /&gt;
If we now build the program at this stage and run it, you would be able to load a &amp;#039;&amp;#039;family&amp;#039;&amp;#039; database into the program using the File|Open menu item. To test this, you can use the same fa.txt database that was developed for the console version of this program. A message appearing in the Messages window will inform you in case the program was able to load a database successfully.&lt;br /&gt;
&lt;br /&gt;
Note that though the dialog would be asking for &amp;#039;&amp;#039;&amp;quot;&amp;#039;&amp;#039;.txt&amp;#039;&amp;#039;&amp;quot;&amp;#039;&amp;#039; files, they should not be confused with common text files used in computers. The files that are to be used are to be formatted exactly as per our programs requirements. Any other file would result in an error.&lt;br /&gt;
&lt;br /&gt;
If the file gets loaded correctly, then the stdIO::writef(...) predicate is called to indicate that result. A GUI program does not have a regular console but Visual Prolog GUI programs automatically provide a Messages which acts as a stdout console. Hence the stdIO::writef(...) predicate results gets presented in the Messages. (If you had closed the window, then you would not be able to se the result). You can even re-size or zoom the Messages window, to suit your taste.&lt;br /&gt;
&lt;br /&gt;
Now you should go back to the Dialog and Window Expert, and ensure that the listeners for the Query|Father, Query|Grandfather and Query|Ancestor of ... menu items are also set as shown below:&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualPrologGui22.png]]&lt;br /&gt;
&lt;br /&gt;
Now for the Query|Father menu item, add the following clause body before the default clause body inserted automatically by Visual Prolog:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;predicates&lt;br /&gt;
    onQueryFather : window::menuItemListener.&lt;br /&gt;
clauses&lt;br /&gt;
    onQueryFather(_Source, _MenuTag):-&lt;br /&gt;
            stdIO::write(&amp;quot;\nfather test\n&amp;quot;),&lt;br /&gt;
            father(X, Y),&lt;br /&gt;
            stdIO::writef(&amp;quot;% is the father of %\n&amp;quot;, Y, X),&lt;br /&gt;
            fail.&lt;br /&gt;
    onQueryFather(_Source, _MenuTag).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the Query|Grandfather... menu item, add the following clause body before the default clause body inserted automatically by Visual Prolog:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;predicates&lt;br /&gt;
    onQueryGrandfather : window::menuItemListener.&lt;br /&gt;
clauses&lt;br /&gt;
onQueryGrandFather(_Source, _MenuTag) :-&lt;br /&gt;
            stdIO::write(&amp;quot;\ngrandFather test\n&amp;quot;),&lt;br /&gt;
            grandfather(X, Y),&lt;br /&gt;
            stdIO::writef(&amp;quot;% is the grandfather of %\n&amp;quot;, Y, X),&lt;br /&gt;
            fail.&lt;br /&gt;
    onQueryGrandFather(_Source, _MenuTag).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Understanding What we have Done So Far==&lt;br /&gt;
&lt;br /&gt;
Let us now pause our tutorial and take a breather (phew!). &amp;quot;Where is the encapsulation?&amp;quot;, - you should ask. Well, we have broken up the code into two parts. There is the non-interactive logical core which we took care of earlier. But those parts which requires inputs from the user, has been squirrelled away in separate portions into &amp;#039;&amp;#039;different&amp;#039;&amp;#039; event handlers. As far as the rest of the program is concerned, it need not be even aware where those event handlers are actually written in the program. Now, let us insert some more interactive code into yet another event handler.&lt;br /&gt;
&lt;br /&gt;
For the Query|Ancestor of ... menu item, add the following clause body before the default clause body inserted automatically by Visual Prolog:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;predicates&lt;br /&gt;
    onQueryAncestorOf : window::menuItemListener.&lt;br /&gt;
clauses&lt;br /&gt;
    onQueryAncestorOf(_Source, _MenuTag) :-&lt;br /&gt;
     X = ancestorDialog::tryGetName(This),&lt;br /&gt;
          stdIO::writef(&amp;quot;\nancestor of % test\n&amp;quot;, X),&lt;br /&gt;
          ancestor(X, Y),&lt;br /&gt;
          stdIO::writef(&amp;quot;% is the ancestor of %\n&amp;quot;, Y, X),&lt;br /&gt;
          fail.&lt;br /&gt;
    onQueryAncestorOf(_Source, _MenuTag).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The strategy for the above code is to acquire a string from a modal dialog box presented by the ancestorDialog which we had created earlier. The above predicate assumes that there is a globally accessible predicate called tryGetName available in the &amp;#039;&amp;#039;ancestorDialog&amp;#039;&amp;#039; module which will return the name of the person whose ancestors we are seeking.&lt;br /&gt;
&lt;br /&gt;
As was seen in the onFileOpen Event Handler, we had sought a string (the filename) returned from a modal dialog. The modal dialog itself was invoked by the predicate vpiCommonDialogs::getFileName(...) It is the same strategy that we are adopting for obtaining a string from the ancestorDialog. The only difference is that vpiCommonDialogs::getFileName(...) gave a built-in standard Windows modal file dialog. But for our home grown ancestorDialog, we would have to do some more coding as we shall shortly see.&lt;br /&gt;
&lt;br /&gt;
On compiling the program, there will be one error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;error c229: Undeclared identifier &amp;#039;ancestorDialog::tryGetName/1-&amp;gt;&amp;#039;&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The reason for this error is because the onQueryAncestorOf predicate is expecting this globally accessible predicate called tryGetName from the module ancestorDialog.pro. But we haven&amp;#039;t written that yet! Let us now get down to rectifying that error.&lt;br /&gt;
&lt;br /&gt;
This predicate is defined within one module, but called from another module. Hence we need to ensure that the declaration is kept not in the .pro. The class declaration file of a module (extension .cl) is one such place. Therefore, let us now open ancestorDialog.cl and insert the following piece of code. (It is a declaration statin called tryGetName is implemented within the module, and that predicate can be called from other modules too.)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;predicates&lt;br /&gt;
    trygetName : (window Parent) -&amp;gt; string Name determ.&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In ancestorDialog.pro, let us now insert the core logic relevant to that module. Just the way we did for Taskwindow.pro, it is inserted just after the following lines:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;implement ancestorDialog inherits dialog&lt;br /&gt;
    open core, vpiDomains&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is the code to be inserted:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;domains&lt;br /&gt;
    optionalString = none(); one(string Value).&lt;br /&gt;
class facts&lt;br /&gt;
    name : optionalString := none().&lt;br /&gt;
clauses&lt;br /&gt;
    tryGetName(Parent) = Name :-&lt;br /&gt;
        name := none(),&lt;br /&gt;
        _ = ancestorDialog::display(Parent),&lt;br /&gt;
        one(Name) = name.&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now there is one last issue which is remaining. We need to change the event handler for the OK button. This is required, so that the dialog would assert the value entered by the user into the &amp;#039;&amp;#039;name&amp;#039;&amp;#039; class facts. If that is not done, then the above predicate will find an empty string.&lt;br /&gt;
&lt;br /&gt;
The default code given by Visual Prolog is shown below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;predicates&lt;br /&gt;
    onOkClick : button::clickResponder.&lt;br /&gt;
clauses&lt;br /&gt;
    onOkClick(_Source) = button::defaultAction.&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code now will have to be changed into the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;predicates&lt;br /&gt;
    onOkClick : button::clickResponder.&lt;br /&gt;
clauses&lt;br /&gt;
    onOkClick(_Source) = button::defaultAction :-&lt;br /&gt;
        Name = idc_ancestordialog_personname:getText(),&lt;br /&gt;
        name := one(Name).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now we have finally finished our program. If you now compile and run the program, you should not get any errors.&lt;br /&gt;
&lt;br /&gt;
==Running the Program==&lt;br /&gt;
&lt;br /&gt;
Once you start the program, you would notice that no activity gets performed immediately, the way it was done in the console program which we had written earlier. As explained somewhere before, starting up a GUI program is like entering a room where the user is free to do things in whichever order he/she chooses. The room simply waits for inputs from the user in whichever order the user decides to give.&lt;br /&gt;
&lt;br /&gt;
Analogously, in our little program, we can invoke the Query|Query Father menu without loading any data. It would not yield any results or any error either because our main logic also takes care of the situation where the data is absent. We can invoke the File|Open... menu item at our choice, and load the family database (the same one which was used in the earlier tutorial).&lt;br /&gt;
&lt;br /&gt;
After that, we can test the Query|Query Father, Query|Query Ancestor and Query|Ancestor of... to see the same results that were obtained in the console program. The results would be displayed in the Messages. (Be careful not to close the Messages window, else the results would not get displayed). The advantage of a GUI program would be recognized when we find that we can run our queries any number of times. Also, we are free to load different data at any point in time.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
In this tutorial, we have gone through the basics of GUI and how a GUI program can easily be developed in Visual Prolog. We found that the IDE (Integrated Development Environment) given by Visual Prolog allows us complete control over all the GUI components we may wish to use. We were able to edit menus, dialogs and toolbars to suit the functionality that we desire.&lt;br /&gt;
&lt;br /&gt;
Then we were able to modularize the Prolog code and insert it into different parts of the program, so that they are safely encapsulated into different listeners and responders. The non-interactive logical core was kept separately.&lt;br /&gt;
&lt;br /&gt;
A GUI program thus developed can then be used in a very flexible manner, with no compulsion to the user regarding the sequence of activities to be performed with the program.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[[Category:Fundamental Visual Prolog Tutorial]]&lt;br /&gt;
[[Category:GUI]]&lt;/div&gt;</summary>
		<author><name>Kasper B H Petersen</name></author>
	</entry>
	<entry>
		<id>https://wiki.visual-prolog.com/index.php?title=Fundamental_Visual_Prolog&amp;diff=4831</id>
		<title>Fundamental Visual Prolog</title>
		<link rel="alternate" type="text/html" href="https://wiki.visual-prolog.com/index.php?title=Fundamental_Visual_Prolog&amp;diff=4831"/>
		<updated>2021-10-06T14:26:47Z</updated>

		<summary type="html">&lt;p&gt;Kasper B H Petersen: /* Step 5: Execute the Program */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{FundamentalPrologNavbar}}&lt;br /&gt;
&lt;br /&gt;
In this tutorial, we will introduce a program that is developed on the Visual Prolog platform. The essential algorithms of the tutorial are the same as those that were developed in [[Fundamental Prolog Part 2]].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Differences between Visual Prolog and traditional Prolog==&lt;br /&gt;
&lt;br /&gt;
The differences between traditional Prolog and Visual Prolog can be broadly divided into these categories:&lt;br /&gt;
&lt;br /&gt;
*Program structure differences: There are distinct, yet easy to understand differences between the structure used in traditional Prolog and that used in Visual Prolog. It essentially comprises of understanding how to mark out the declarations from the definitions, and to indicate the main &amp;#039;&amp;#039;Goal&amp;#039;&amp;#039; that the program has to seek using specific keywords.&lt;br /&gt;
&lt;br /&gt;
*File considerations: Visual Prolog provides various facilities to organize the structure of the program into different kinds of files.&lt;br /&gt;
&lt;br /&gt;
*Scope access issues: A Visual Prolog program can pick up functionality developed in other modules using a concept called &amp;#039;&amp;#039;scope identification&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
*Object orientation: A Visual Prolog program can be written as an object-oriented program, using classic object oriented features.&lt;br /&gt;
&lt;br /&gt;
===Program Structure Differences===&lt;br /&gt;
&lt;br /&gt;
====Declarations and Definitions====&lt;br /&gt;
&lt;br /&gt;
In Prolog, when we need to use a predicate we simply do so without any prior indication to the Prolog engine about our intention. For example, in the earlier tutorial the &amp;lt;vp&amp;gt;grandFather&amp;lt;/vp&amp;gt; predicate&amp;#039;s clause was directly written using the traditional Prolog predicate head and body construction. We did not bother to inform the engine in the code that such a predicate construction is to be expected later.&lt;br /&gt;
&lt;br /&gt;
Similarly, when a compound domain is used in traditional Prolog, we can use it without first warning the Prolog engine about our intention to use the domain. We simply use a domain the moment we feel the need for it.&lt;br /&gt;
&lt;br /&gt;
However, in Visual Prolog, before writing the code for the clause body of a predicate we first need to declare the existence of such a predicate. Similarly, before using any domains, they need to be declared. The reason such forewarnings are required in Visual Prolog is to ensure that runtime exceptions are converted into compile time errors as far as possible.&lt;br /&gt;
&lt;br /&gt;
By &amp;#039;&amp;#039;&amp;quot;runtime exceptions&amp;quot;&amp;#039;&amp;#039;, we mean issues that turn up when a program is run. For example, if you had intended to use an integer as the argument of a functor, and instead of the integer you had erroneously used a real number, it would become a &amp;#039;&amp;#039;runtime&amp;#039;&amp;#039; error in programs written using most other Prolog compilers and the program would fail there. When you declare the predicates and domains in advance, this kind of positional grammar (which argument belongs to which domain), etc. is made available to the compiler. Therefore, when Visual Prolog performs a compilation, it checks the program quite thoroughly to weed out such grammatical and other mistakes.&lt;br /&gt;
&lt;br /&gt;
Because of this feature in Visual Prolog, the overall efficiency of a programmer improves. The programmer does not have to wait till the program is actually executed to detect a bug. In fact, those of you who are experienced in programming would understand what a life-saver this can be; often, the particular sequence of events that causes a &amp;#039;&amp;#039;runtime exception&amp;#039;&amp;#039; to happen may be so elusive that the bug may only turn up after several years, or it may manifest itself in some critical or other embarrassing situations!&lt;br /&gt;
&lt;br /&gt;
All this implies that the compiler &amp;#039;&amp;#039;&amp;#039;has&amp;#039;&amp;#039;&amp;#039; to be given explicit instructions regarding the predicates and domains that exist in the code using appropriate declarations before they are defined.&lt;br /&gt;
&lt;br /&gt;
====Keywords====&lt;br /&gt;
&lt;br /&gt;
A Visual Prolog program consists of Prolog code which is punctuated into different &amp;#039;&amp;#039;&amp;#039;sections&amp;#039;&amp;#039;&amp;#039; by appropriate keywords that inform the compiler the code it has to generate. For example, there are keywords that differentiate the &amp;#039;&amp;#039;declarations&amp;#039;&amp;#039; from the &amp;#039;&amp;#039;definitions&amp;#039;&amp;#039; of predicates and domains. Usually, each section is preceded by a keyword. There is normally no keyword which signifies the ending of a particular section. The presence of another keyword indicates the ending of the previous section, and the starting of the next one.&lt;br /&gt;
&lt;br /&gt;
The exception to this rule, are the keywords &amp;quot;implement&amp;quot; and &amp;quot;end implement&amp;quot;. The code contained between these two keywords indicates the code to be used for a particular class. Those of you who do not understand the concept of a &amp;quot;class&amp;quot; can, for now, think of it as a module or a section of the overall program code.&lt;br /&gt;
&lt;br /&gt;
For the purpose of this tutorial, we&amp;#039;ll introduce only the following keywords (given below). We are also giving the purpose behind these keywords, and the actual syntax can be easily learnt from the documentation. There are other keywords also in Visual Prolog, and those can easily be picked up in later tutorials and the documentation.&lt;br /&gt;
&lt;br /&gt;
The list of the keywords that you need to know in this tutorial is the following:&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;implement&amp;#039;&amp;#039;&amp;#039; and &amp;#039;&amp;#039;&amp;#039;end implement&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
:Among all the keywords discussed here, this is the only one, which exists as a pair. Visual Prolog treats the code written between these two keywords as the code that belongs to one class. The name of the class MUST be given after the implement keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;open&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
:This keyword is used to extend the &amp;#039;&amp;#039;scope visibility&amp;#039;&amp;#039; of the class. It is to be used just after the implement keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;constants&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
:This keyword is used to mark a section of the code that defines some commonly used values in the program code. For example, if the string literal &amp;quot;PDC Prolog&amp;quot; is to be used in multiple locations throughout the code, then you can define a mnemonic (a short-form, easily remembered word) for the same thus:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&amp;lt;vip&amp;gt;constants&lt;br /&gt;
    pdc = &amp;quot;PDC Prolog&amp;quot;.&amp;lt;/vip&amp;gt;&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
:Note that the definition of a constant ends in a period (.). Unlike a Prolog variable, a constant should be a word starting with a lower case letter.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;domains&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
:This keyword is used to mark a section declaring the domains that would be used in the code. There are many variations for the syntax of such domain declarations, and they cater to the all the possible kinds of domains that would be used later on in the code. As this tutorial is a basic one, we shall not get into the finer details of the domain declarations that can be possible.&lt;br /&gt;
&lt;br /&gt;
:To summarize here, you would be declaring the functor that would be used for the domain and the kind of domains that would form its arguments. Functors and compound domains were explained in detail in the previous part of the Tutorial.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;class facts&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
:This keyword designates a section, which declares the facts that would be used later on in the code of the program. Each fact is declared with the name used to signify the fact and the arguments that are used for the respective facts along with the domains that those arguments belong to.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;class predicates&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
:This section contains the declarations of the predicates that would be later defined in the clauses section of the code. Once again, the names that would be used for these predicates along with the arguments and the domains, to which the arguments belong to, would be indicated in this section.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;clauses&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
:Of all the sections that are present in a Visual Prolog code, this section is the one that closely mimics a traditional Prolog program. It contains the actual &amp;#039;&amp;#039;definitions&amp;#039;&amp;#039; of the previously declared predicates. And you would find that the predicates used here would follow the syntax as declared in the &amp;#039;&amp;#039;class predicates&amp;#039;&amp;#039; section.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;goal&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
:This section defines the main entry point into a Visual Prolog program. A more detailed explanation is given below.&lt;br /&gt;
&lt;br /&gt;
====Goal====&lt;br /&gt;
&lt;br /&gt;
In traditional Prolog, whenever a predicate is defined in the code, the Prolog Engine can be instructed to start the code execution from that predicate onwards. However, that is not the case with Visual Prolog. Being a &amp;#039;&amp;#039;compiler&amp;#039;&amp;#039; it has the responsibility of producing efficiently executing code for the program you write. This code would not be actually executing at the same time the &amp;#039;&amp;#039;compiler&amp;#039;&amp;#039; is doing its work. Hence, the &amp;#039;&amp;#039;compiler&amp;#039;&amp;#039; needs to know beforehand the exact predicate from which the code execution would start, so that later on when the program is called to perform, it can do so from the correct starting point. As you may have guessed, the compiled program can run independently without the Visual Prolog compiler or the IDE itself.&lt;br /&gt;
&lt;br /&gt;
In order to do that, there is a special section indicated by the keyword &amp;#039;&amp;#039;Goal&amp;#039;&amp;#039;. Think of it as a special predicate that you would write without arguments. That predicate is the one from which the entire program execution will start.&lt;br /&gt;
&lt;br /&gt;
===File Considerations===&lt;br /&gt;
&lt;br /&gt;
Many times, it may become cumbersome to put all the parts of the program into one file itself. It may even make the program unreadable and sometimes incorrect. Visual Prolog has the capability of dividing the program code into separate files using the IDE (Integrated Development Environment) and it is possible to write neat pieces of code into separate files using that IDE. When it is done in that manner, things that are to be used commonly can be accessed across files. E.g. If you have a domain that is to be used in multiple files, then the declaration of that domain is done in a separate file, and that file is then accessed from other files.&lt;br /&gt;
&lt;br /&gt;
However, for the purpose of simplifying this particular tutorial, we shall predominantly be using only one file to develop the program code. In the course of constructing the program, the IDE would automatically create some more files which we can ignore for the time being. We can learn about them in future tutorials.&lt;br /&gt;
&lt;br /&gt;
===Scope Access Issues===&lt;br /&gt;
&lt;br /&gt;
Visual Prolog divides the total program code into separate parts, each part defining one class. In object oriented languages, a class is a package of code and its associated data which is put together. This requires more explanation which would be available in later tutorials. As noted earlier, for those of you who are not familiar with object oriented programs, you can think of a &amp;#039;&amp;#039;class&amp;#039;&amp;#039; loosely as being synonymous to &amp;#039;&amp;#039;modules&amp;#039;&amp;#039;. Normally, Visual Prolog defines each class in its own separate file.&lt;br /&gt;
&lt;br /&gt;
During the program execution, it often so happens that the program may need to invoke a predicate that is actually defined in another class (file). Similarly, data (constants) or domains defined in a class may need to be accessed from a different file.&lt;br /&gt;
&lt;br /&gt;
Visual Prolog allows such cross class code/data references using a concept called scope access. This can be understood by an example. Suppose there is a predicate called pred1 defined in a class called class1 (which is written down in another file using the IDE), and we need to call that predicate in the clause body of some other predicate, pred2 in a different file (say class2) then this is how pred1 would be called within the clause body of pred2 :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;clauses&lt;br /&gt;
    pred3:-&lt;br /&gt;
        ...&lt;br /&gt;
        !.&lt;br /&gt;
&lt;br /&gt;
    pred2:-&lt;br /&gt;
        class1::pred1, % pred1 is not known in this class. It is defined in some other class, hence a class qualifier is needed&lt;br /&gt;
        pred3,&lt;br /&gt;
        ...&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, you can see that the clause body of pred2 calls two predicates pred1 and pred3. As pred1 is defined in another file (which defines class1), the word class1 with the token &amp;#039;&amp;#039;&amp;#039;::&amp;#039;&amp;#039;&amp;#039; (two colons) precedes the word pred1. This can be called as a class qualifier.But the predicate pred3 is defined within the same file as pred2 itself. Hence there is no need to indicate class2:: prior to the predicate call for pred3.&lt;br /&gt;
&lt;br /&gt;
This behavior is technically explained thus: The &amp;#039;&amp;#039;scope visibility&amp;#039;&amp;#039; of pred3 is within the same scope of pred2. Hence there is no need to clarify that pred3 is from the same class as pred2. The compiler would automatically look for the definition of pred3 within the same scope area as defined for class2.&lt;br /&gt;
&lt;br /&gt;
The scope area of a particular class definition is restricted to the class that is implemented in a particular file (i.e. code that is written within the implement &amp;#039;&amp;#039;-&amp;#039;&amp;#039; end implement keywords). The predicates defined therein can call each other without the class qualifier and the double colon (::) token preceding it.&lt;br /&gt;
&lt;br /&gt;
The scope area of a class can be extended by using the open keyword. This keyword informs the compiler to bring in names (of predicates / constants / domains) that were defined in other files. If a scope area is extended, then we need not write the class qualifier with the double colon.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;open class1&lt;br /&gt;
            ...&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    pred3:-&lt;br /&gt;
        ...&lt;br /&gt;
        !.&lt;br /&gt;
&lt;br /&gt;
    pred2:-&lt;br /&gt;
        pred1, %Note: &amp;quot;class1::&amp;quot; qualifier is not needed anymore, as the scope area is extended using the &amp;#039;open&amp;#039; keyword&lt;br /&gt;
        pred3,&lt;br /&gt;
        ...&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Object Orientation===&lt;br /&gt;
&lt;br /&gt;
The current version of Visual Prolog is a strongly object oriented language. The ENTIRE code which is developed for a program is put into appropriate classes, as needed. This happens by default, even if you are not interested in the object oriented features of the language. You would notice this feature in the example given in this tutorial also. The code is inserted into a class called &amp;quot;family1&amp;quot; even though we would eventually not use any objects created from that class. Instead, we would use publicly accessible predicates of the code within that class directly.&lt;br /&gt;
&lt;br /&gt;
This tutorial will not handle the object oriented features of the language. Future tutorials would extend this concept, and even actually use the object oriented features.&lt;br /&gt;
&lt;br /&gt;
== A Full Fledged Example: family1.vipprj ==&lt;br /&gt;
&lt;br /&gt;
The result of following this tutuorial is available as an example in the Visual Prolog installation, use &amp;#039;&amp;#039;&amp;#039;Help -&amp;gt; Install Examples...&amp;#039;&amp;#039;&amp;#039; to install the examples.  This particular example is then in the folder: &amp;#039;…\_tutorial\familyfamily1&amp;#039;, where &amp;#039;…&amp;#039; is the folder in which you installed the examples.&lt;br /&gt;
&lt;br /&gt;
Here we will however create it from scratch.&lt;br /&gt;
&lt;br /&gt;
Let us now put all the knowledge we&amp;#039;ve gathered together to create our first Visual Prolog program. This will contain the same basic logic that was explored in the Tutorial &amp;quot;Fundamental Prolog. Part 2&amp;quot;. All the code that is to be written for this tutorial is shown below. The actual code writing will be done using the Visual Prolog IDE (Integrated Development Environment). There are some more files that are needed for the tutorial, but those would automatically be generated and maintained by the IDE. The step by step instructions (using screenshots) for utilizing the IDE to develop the program will shortly follow.&lt;br /&gt;
&lt;br /&gt;
But first of all, let us acquaint ourselves with the main code of the program:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;implement main&lt;br /&gt;
&lt;br /&gt;
domains&lt;br /&gt;
    gender = female; male.&lt;br /&gt;
&lt;br /&gt;
class facts - familyDB&lt;br /&gt;
    person : (string Name, gender Gender).&lt;br /&gt;
    parent : (string Person, string Parent).&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    father : (string Person, string Father) nondeterm anyflow.&lt;br /&gt;
clauses&lt;br /&gt;
    father(Person, Father) :-&lt;br /&gt;
        parent(Person, Father),&lt;br /&gt;
        person(Father, male).&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    grandFather : (string Person [out], string GrandFather [out]) nondeterm.&lt;br /&gt;
clauses&lt;br /&gt;
    grandFather(Person, GrandFather) :-&lt;br /&gt;
        parent(Person, Parent),&lt;br /&gt;
        father(Parent, GrandFather).&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    ancestor : (string Person, string Ancestor [out]) nondeterm.&lt;br /&gt;
clauses&lt;br /&gt;
    ancestor(Person, Ancestor) :-&lt;br /&gt;
        parent(Person, Ancestor).&lt;br /&gt;
    ancestor(Person, Ancestor) :-&lt;br /&gt;
        parent(Person, P1),&lt;br /&gt;
        ancestor(P1, Ancestor).&lt;br /&gt;
&lt;br /&gt;
class predicates&lt;br /&gt;
    reconsult : (string FileName).&lt;br /&gt;
clauses&lt;br /&gt;
    reconsult(FileName) :-&lt;br /&gt;
        retractFactDB(familyDB),&lt;br /&gt;
        file::consult(FileName, familyDB).&lt;br /&gt;
&lt;br /&gt;
clauses&lt;br /&gt;
    run() :-&lt;br /&gt;
        console::init(),&lt;br /&gt;
        stdio::write(&amp;quot;Load data\n&amp;quot;),&lt;br /&gt;
        reconsult(@&amp;quot;..\fa.txt&amp;quot;),&lt;br /&gt;
        stdio::write(&amp;quot;\nfather test\n&amp;quot;),&lt;br /&gt;
        father(X, Y),&lt;br /&gt;
        stdio::writef(&amp;quot;% is the father of %\n&amp;quot;, Y, X),&lt;br /&gt;
        fail.&lt;br /&gt;
&lt;br /&gt;
    run() :-&lt;br /&gt;
        stdio::write(&amp;quot;\ngrandFather test\n&amp;quot;),&lt;br /&gt;
        grandFather(X, Y),&lt;br /&gt;
        stdio::writef(&amp;quot;% is the grandfather of %\n&amp;quot;, Y, X),&lt;br /&gt;
        fail.&lt;br /&gt;
&lt;br /&gt;
    run() :-&lt;br /&gt;
        stdio::write(&amp;quot;\nancestor of Pam test\n&amp;quot;),&lt;br /&gt;
        X = &amp;quot;Pam&amp;quot;,&lt;br /&gt;
        ancestor(X, Y),&lt;br /&gt;
        stdio::writef(&amp;quot;% is the ancestor of %\n&amp;quot;, Y, X),&lt;br /&gt;
        fail.&lt;br /&gt;
&lt;br /&gt;
    run() :-&lt;br /&gt;
        stdio::write(&amp;quot;End of test\n&amp;quot;).&lt;br /&gt;
&lt;br /&gt;
end implement main&lt;br /&gt;
&lt;br /&gt;
goal&lt;br /&gt;
    mainExe::run(main::run).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Step 1: Create a New Console Project in the IDE===&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Step 1a.&amp;#039;&amp;#039;&amp;#039; After starting the Visual Prolog IDE, click on the New menu item from the Project menu.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Step 1b.&amp;#039;&amp;#039;&amp;#039; A dialog would be presented to you. Enter all the relevant information. Ensure that the Project Kind is &amp;#039;&amp;#039;Console&amp;#039;&amp;#039; and NOT &amp;#039;&amp;#039;GUI&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualProlog2.png]]&lt;br /&gt;
&lt;br /&gt;
===Step 2: Build an Empty Project===&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Step 2a.&amp;#039;&amp;#039;&amp;#039; When the project is just created, the IDE would display the following project window. At this point in time, it does not have any clue about what files the project is dependent on. It does, however create the basic source code files for the project.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Step 2b.&amp;#039;&amp;#039;&amp;#039; Use the Build menu item of the Build menu, to compile and link the empty project to create an executable file which basically does not do anything. (At this point it time, it would not generate any errors either)&lt;br /&gt;
&lt;br /&gt;
While building the project, take a look at the messages that are dynamically displayed in the &amp;#039;&amp;#039;&amp;#039;Messages&amp;#039;&amp;#039;&amp;#039; window of the IDE. (In the case the &amp;#039;&amp;#039;&amp;#039;Messages&amp;#039;&amp;#039;&amp;#039; window is not visible, you can turn it on using the Window menu of the IDE) You will notice that the IDE intelligently pulls in ALL the necessary PFC (Prolog Foundation Classes) modules into your project. PFC classes are those classes which contains the basic functionality on which your programs would be built.&lt;br /&gt;
&lt;br /&gt;
===Step 3: Populate the main.pro with the Actual Code===&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Step 3a.&amp;#039;&amp;#039;&amp;#039; The default code inserted by the IDE is very basic and does not do anything useful. You would need to delete the entire code and copy and paste the actual code of main.pro (given in this tutorial) into that window.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualProlog5.png]]&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Step 3b.&amp;#039;&amp;#039;&amp;#039; After you perform the copy-paste operation, the main.pro window would now look as shown below:&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualProlog6.png]]&lt;br /&gt;
&lt;br /&gt;
===Step 4: Rebuild the Code===&lt;br /&gt;
&lt;br /&gt;
Re-invoke the Build menu command, and the IDE will notice that the source code has changed, and will take measures to appropriately recompile the correct sections. If you use the Build All menu command, then &amp;#039;&amp;#039;ALL&amp;#039;&amp;#039; the modules would be recompiled. For large programs this can consume some time. Build All is often used ONLY at the end of a series of smaller compilations; just to ensure that everything is in ship-shape order.&lt;br /&gt;
&lt;br /&gt;
During the &amp;#039;&amp;#039;Build&amp;#039;&amp;#039; process, the IDE not only does the compilation; but it also determines whether the project may need any other missing PFC modules, and inserts those and re-starts the compilation process if required. This can be seen in the messages appearing in the Messages window, where you&amp;#039;ll notice the IDE was forced to build the project &amp;#039;&amp;#039;twice&amp;#039;&amp;#039; because of some additional include statements.&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualProlog7.png]]&lt;br /&gt;
&lt;br /&gt;
===Step 5: Execute the Program===&lt;br /&gt;
&lt;br /&gt;
We now have our first true application complied using Visual Prolog. In order to test the application we&amp;#039;ve just compiled, you can run the program using the &amp;#039;&amp;#039;&amp;#039;Build -&amp;gt; Run&amp;#039;&amp;#039;&amp;#039; menu command. However, in our case this would result in an error. The reason is that our little program is trying to read a text file (fa.txt) for its functioning. That text file contains the actual data regarding persons which our program will process. We&amp;#039;ll come to the syntax of that file a bit later.&lt;br /&gt;
&lt;br /&gt;
We need to now write that text file using some text editor and place it in the project root folder.&lt;br /&gt;
&lt;br /&gt;
You cannot create such a file directly in the IDE itself, but you can save an existing files with a new name (using &amp;#039;&amp;#039;&amp;#039;File -&amp;gt; Save as ...&amp;#039;&amp;#039;&amp;#039;) and then edit that file.  Give the file the name &amp;#039;&amp;#039;fa.txt&amp;#039;&amp;#039;. After you have saved the file you can add it to the project by selecting &amp;#039;&amp;#039;&amp;#039;File -&amp;gt; Add...&amp;#039;&amp;#039;&amp;#039;. The advantage of adding it to the project is that it will be available for any subsequent debugging, etc.&lt;br /&gt;
&lt;br /&gt;
The contents of the file should be as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;clauses&lt;br /&gt;
    person(&amp;quot;Judith&amp;quot;,female).&lt;br /&gt;
    person(&amp;quot;Bill&amp;quot;,male).&lt;br /&gt;
    person(&amp;quot;John&amp;quot;,male).&lt;br /&gt;
    person(&amp;quot;Pam&amp;quot;,female).&lt;br /&gt;
    parent(&amp;quot;John&amp;quot;,&amp;quot;Judith&amp;quot;).&lt;br /&gt;
    parent(&amp;quot;Bill&amp;quot;,&amp;quot;John&amp;quot;).&lt;br /&gt;
    parent(&amp;quot;Pam&amp;quot;,&amp;quot;Bill&amp;quot;).&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Though it is a data file, you would notice that the syntax of the file is VERY similar to regular Prolog code! Even though the program is now compiled and is now in a binary format; you can change the output by simply changing the crucial data the program is processing. And that data is written into this text file using the same syntax as Prolog. Thus Visual Prolog emulates the &amp;#039;&amp;#039;dynamic&amp;#039;&amp;#039; code writing capability of traditional Prolog. Albeit, not all features are available but at least complicated domains such as those in this example can definitely be given.&lt;br /&gt;
&lt;br /&gt;
The syntax used in fa.txt MUST be compatible with the domain definitions of the program. E.g. The functor used for defining a person MUST be &amp;#039;&amp;#039;person&amp;#039;&amp;#039; and not anything else; else appropriate compound domain representing that functor would not get initialized. (We had covered the topic of functors and compound domains in an earlier tutorial).&lt;br /&gt;
&lt;br /&gt;
Now, when you run the program using the &amp;#039;&amp;#039;&amp;#039;Build -&amp;gt; Run in Window&amp;#039;&amp;#039;&amp;#039; menu command, this is what you&amp;#039;ll see:&lt;br /&gt;
&lt;br /&gt;
:[[Image:FundamentalVisualProlog8.png]]&lt;br /&gt;
&lt;br /&gt;
The program processes the information in the file fa.txt and works out the logical sequence of the parentages of people given there.&lt;br /&gt;
&lt;br /&gt;
===A Round up of the Program===&lt;br /&gt;
&lt;br /&gt;
The logic of the program is very simple. We had discussed it in an earlier tutorial, where we explained how the correct representation of data can help yield the appropriate results in a Prolog program. Let us now discuss the manner in which this logic works.&lt;br /&gt;
&lt;br /&gt;
At start up, the main predicate will be invoked directly. This in turns branches off to the run predicate. The first thing the run predicate will do is to read in the data which is written in the file fa.txt. Once the data is in place, the program systematically progresses from one test to another to process the data and write out the conclusions of that test onto the console.&lt;br /&gt;
&lt;br /&gt;
The mechanisms for processing the data are standard mechanisms of backtracking and recursions. This tutorial is not the place for a detailed explanation of how Prolog works, but here is a short summary of the internal workings.&lt;br /&gt;
&lt;br /&gt;
When the run predicate is calling the father predicate, it does not stop at the first satisfactory ending of the father predicate. The invoking of a fail at the end of the predicate, forces the Prolog engine to seek another pass through the father predicate. Such a behavior is called &amp;#039;&amp;#039;backtracking&amp;#039;&amp;#039;, because the Prolog engine literally seems to backtrack over code which had earlier executed.&lt;br /&gt;
&lt;br /&gt;
This happens recursively (i.e. as a repetitive process or cyclically), and at each cycle the father predicate yields the next result. Eventually all the possible definitions of &amp;quot;fathers&amp;quot; given in the data are exhausted, and the run predicate would have no choice but carry over to the next clause body of the run predicate.&lt;br /&gt;
&lt;br /&gt;
The father predicate (as well as some other predicates) has been declared to be non-deterministic. The keyword nondeterm can be used to declare non-deterministic predicates; i.e. predicates that can yield multiple answers using backtracking.&lt;br /&gt;
&lt;br /&gt;
If the no keyword is used in a predicate declaration, then the predicate has got the procedure mode, which can give only one solution, and the father predicate will stop after yielding the first result and cannot be re-entered into. Also, one must be careful in the usage of the cut (!) in the clause bodies of such non-deterministic predicates. If there is a cut at the end of the clause body of the father predicate, yet again; the predicate will yield only one solution (even if it has been declared to be non-deterministic).&lt;br /&gt;
&lt;br /&gt;
The anyflow flow-pattern tells the compiler that the parameters that are given for the predicate could be either free or bound, with no restrictions whatsoever. That means, with the same definition of the father predicate, it would be possible to both yield the father&amp;#039;s name (in case the name of the offspring was bound) OR the offspring&amp;#039;s name (in case the name of the father was bound). It can also handle situations where both are bound; in which case the predicate will check if such a relationship exists in the data.&lt;br /&gt;
&lt;br /&gt;
And; to state the obvious; the anyflow flow pattern can also accommodate a situation where both the parameters of the father predicate are free variables. In such a case, the father predicate will yield the various combinations of father+offspring present in the data the program has learnt (through consulting the fa.txt file) to the enquirer. The last usage is what is performed in the run predicate, as seen in the code snippet below. You would notice that the variables X and Y given to the father predicate are not bound when the father predicate is called.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;vip&amp;gt;clauses&lt;br /&gt;
    run():-&lt;br /&gt;
        console::init(),&lt;br /&gt;
        stdio::write(&amp;quot;Load  data\n&amp;quot;),&lt;br /&gt;
        reconsult(&amp;quot;fa.txt&amp;quot;),&lt;br /&gt;
        stdio::write(&amp;quot;\nfather test\n&amp;quot;),&lt;br /&gt;
        father(X,Y),&lt;br /&gt;
        stdio::writef(&amp;quot;% is the father of %\n&amp;quot;, Y, X),&lt;br /&gt;
        fail.&amp;lt;/vip&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
In this lesson we learnt that programs written in Visual Prolog are often very similar to those written in traditional Prolog. There are several keywords that are used to differentiate the various parts of a Visual Prolog source code. Though Visual Prolog is an object-oriented language, it is possible to develop code which avoids the language&amp;#039;s object-oriented features. A complete console-based application (family1) was developed in this tutorial, which explains, how to create such a program.&lt;br /&gt;
&lt;br /&gt;
We also found that it is possible to emulate the dynamic working of a traditional Prolog program by keeping part of the code as a data file outside the main binary compiled application. The syntax of such a data file closely follows Prolog syntax.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
[[ru:Основы Системы Visual Prolog]]&lt;br /&gt;
[[Category:Fundamental Visual Prolog Tutorial]]&lt;/div&gt;</summary>
		<author><name>Kasper B H Petersen</name></author>
	</entry>
</feed>