Основы Системы Visual Prolog

Материал из wikiru.visual-prolog.com
Основы Visual Prolog


В этом руководстве мы представляем программу, разработанную на платформе системы программирования Visual Prolog. Алгоритмы, используемые в руководстве , - те же, что и в руководстве "Fundamental Prolog" (Часть 2).

Отличия между Visual Prolog и традиционным Прологом

Различия между традиционным Прологом и Visual Prolog можно провести по следующим категориям:

  • Различия в структуре программы:
    Различия между Visual Prolog и традиционным Прологом имеются, но они не существенны. Они сводятся к пониманию того, как различаются декларации (declarations) от определений (definitions), а также к явному выделению цели Goal. Все это поддержано специальными ключевыми словами.
  • Файловая структура программы::
    Visual Prolog предоставляет возможности структуризации программ с использованием файлов различного типа.
  • Границы видимости:
    Программа системы Visual Prolog может поддерживать функционирование, располагающееся в различных модулях с использованием концепции идентификация пространств.
  • Объектная ориентированность:
    Программа на языке Visual Prolog может быть написана как объектно ориентированная программа с использованием классических свойств объектно-ориентированной парадигмы.

Различия в структуре программ

Декларации и Определения

В Прологе, когда необходимо использовать предикат, то это делается без каких-либо предварительных указаний движку Пролога о таких намерениях. Например, в предыдущих руководствах клауз предиката grandFather (дедушка) был непосредственно записан с использованием традиционной для Пролога конструкции голова-тело. Мы не беспокоились о том, чтобы в тексте программы предупредить движок явно, что такая конструкция придиката потребуется.

Аналогично, когда в традиционном Прологе требуется использовать составной домен, мы можем его использовать без предупреждения движка по поводу этого намерения. Мы просто используем домен тогда, когда в этом возникает необходимость.

Однако, в Visual Prolog, перед написанием кода для тела клауза предиката мы должны сначала объявить о существовании такого предиката компилятору. Аналогично, перед использованием любых доменов они должны быть объявлены и представлены компилятору.

Причиной такой необходимости в предупреждениях является попытка как можно раньше обнаружить возможность исключений периода исполнения.

Под "исключениями периода исполнения (runtime exceptions)", мы понимаем события, возникающие только во время исполнения программы. Например, если Вы вознамерились использовать целое число в качестве аргумента функтора, а вместо этого вы по ошибке использовали вещественное число, то в процессе исполнения возникла бы ошибка периода исполнения (в программах, написанных для ряда компиляторов, не не для Visual Prolog) и программа в этом случае завершилась бы неуспешно.

Когда Вы объявляете предикаты или доменты, которые определены, то появляется своего рода позиционная грамматика (к какому домену принадлежит какой аргумент), доступная компилятору. Более того, когда Visual Prolog выполняет компиляцию, он тщательно проверяет программу на наличие таких грамматических ошибок, наряду с другими.

Благодяря этому свойству Visual Prolog, повышается конечная эффективность программиста. Программист не должен ждать, когда реально работаящая программа совершит ошибку. Действительно, те из Вас, кто имеет опыт в программировании, понимает насколько этот код безопасен. Часто конкретная последовательность событий, приводящая к исключению периода исполнения кажется настолько неуловимой, что ошибка может проявиться через много лет, или она может заявить о себе в критической ситуации и привести к непредсказуемым последствиям!

Все это автоматически ведет к тому, что компилятор должен получать точные инструкции по поводу предикатов и доменов в виде соответствующих объявлений, которые должны предшествовать определениям.

Keywords

A Visual Prolog program consists of Prolog code which is punctuated into different sections by appropriate keywords that inform the compiler the code it has to generate. For example, there are keywords that differentiate the declarations from the definitions 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.

The exception to this rule, are the keywords "implement" and "end implement" 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 "class" can, for now (i.e. in this tutorial), think of it as a module or a section of the overall program code.

For the purpose of this tutorial, we'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.

The list of the keywords that you need to know in this tutorial is the following:

implement and end implement

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.

open

This keyword is used to extend the scope visibility of the class. It is to be used just after the implement keyword.

constants

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 "PDC Prolog" 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:

constants
pdc="PDC Prolog".

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.

domains

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.

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.

class facts

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.

class predicates

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.

clauses

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 definitions of the previously declared predicates. And you would find that the predicates used here would follow the syntax as declared in the class predicates section.

goal

This section defines the main entry point into a Visual Prolog program. A more detailed explanation is given below.

Goal

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 compiler 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 compiler is doing its work. Hence, the compiler 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.

In order to do that, there is a special section indicated by the keyword Goal. 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.

File Considerations

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.

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.

Scope Access Issues

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 class loosely as being synonymous to modules. Normally, Visual Prolog defines each class in its own separate file.

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.

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 :

clauses
    pred3:-
        ...
        !.
 
    pred2:-
        class1::pred1, %pred1 is not known in this file. It is defined in some other file, hence a class qualifier is needed
        pred3,
        ...

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 :: (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.

This behavior is technically explained thus: The scope visibility 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.

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 - end implement keywords). The predicates defined therein can call each other without the class qualifier and the double colon (::) token preceding it.

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.

open class1
            ...
 
clauses
    pred3:-
        ...
        !.
 
    pred2:-
        pred1, %Note: "class1::" qualifier is not needed anymore, as the scope area is extended using the 'open' keyword
        pred3,
        ...

Object Orientation

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 "family1" 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.

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.

A Full Fledged Example: family1.prj6

Download: Source files of the example project used in this tutorial.<img alt src="../tut11/images/tut11_dot.gif" border="0" width="1" height="1">

Let us now put all the knowledge we've gathered together to create our first Visual Prolog program. This will contain the same basic logic that was explored in the Tutorial "Fundamental Prolog. Part 2". All the code that is to be written for this tutorial is shown below. It has to be written into the file called family1.pro. 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.

But first of all, let us acquaint ourselves with the main code of the program:

implement family1
    open core
 
constants
    className = "family1".
        classVersion = "$JustDate: $$Revision: $".
 
clauses
    classInfo(className, classVersion).
 
domains
    gender = female(); male().
 
class facts - familyDB
    person : (string Name, gender Gender).
    parent : (string Person, string Parent).
 
class predicates
    father : (string Person, string Father) nondeterm anyflow.
clauses
    father(Person, Father) :-
        parent(Person, Father),
        person(Father, male()).
 
class predicates
    grandFather : (string Person, string GrandFather) nondeterm anyflow.
clauses
    grandFather(Person, GrandFather) :-
        parent(Person, Parent),
        father(Parent, GrandFather).
 
class predicates
    ancestor : (string Person, string Ancestor) nondeterm anyflow.
clauses
    ancestor(Person, Ancestor) :-
        parent(Person, Ancestor).
    ancestor(Person, Ancestor) :-
        parent(Person, P1),
        ancestor(P1, Ancestor).
 
class predicates
    reconsult : (string FileName).
clauses
    reconsult(FileName) :-
        retractFactDB( familyDB),
        file::consult(FileName, familyDB).
 
clauses
    run():-
        console::init(),
        stdIO::write("Load data\n"),
        reconsult("fa.txt"),
        stdIO::write("\nfather test\n"),
        father(X, Y),
            stdIO::writef("% is the father of %\n", Y, X),
        fail.
    run():-
        stdIO::write("\ngrandFather test\n"),
        grandFather(X, Y),
            stdIO::writef("% is the grandfather of %\n", Y, X),
        fail.
    run():-
        stdIO::write("\nancestor of Pam test\n"),
        X = "Pam",
        ancestor(X, Y),
            stdIO::writef("% is the ancestor of %\n", Y, X),
        fail.
    run():-
        stdIO::write("End of test\n").
end implement family1
 
goal
mainExe::run(family1::run).

Step 1: Create a New Console Project in the IDE

Step 1a. After starting the Visual Prolog IDE, click on the New menu item from the Project menu.

FundamentalVisualProlog1.jpg

Step 1b. A dialog would be presented to you. Enter all the relevant information. Ensure that the UI Strategy is Console and NOT GUI.

FundamentalVisualProlog2.jpg

Step 2: Build an Empty Project

Step 2a. 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.

Step 2b. 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)

While building the project, take a look at the messages that are dynamically displayed in the Messages window of the IDE. (In the case the Messages 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.

Step 3: Populate the family1.pro with the Actual Code

Step 3a. 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 family1.pro (given in this tutorial) into that window.

FundamentalVisualProlog5.jpg

Step 3b. After you perform the copy-paste operation, the family1.pro window would now look as shown below:

FundamentalVisualProlog6.jpg

Step 4: Rebuild the Code

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 ALL 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.

During the Build 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'll notice the IDE was forced to build the project twice because of some additional include statements.

Файл:FundamentalVisualProlog7.jpg

Step 5: Execute the Program

We now have our first true application complied using Visual Prolog. In order to test the application we've just compiled, you can run the program using the Build | Run in Window 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'll come to the syntax of that file a bit later.

We need to now write that text file using some text editor and place it in the same directory where the executable is now residing. Normally, the executable would reside in the sub-folder called exe from the main project folder.

Let us create such a file using the IDE itself. Use the File | New menu command. The Create Project Item window will appear. Select Text file from the list on the left hand side. Then select the appropriate directory where the file is to reside (The same directory where the executable file family1.exe is present). Then, give the filename fa.txt and click on the Create button of the dialog. Till the filename is given, the Create button would be grayed (disabled). Make sure that the checkbox: Add to project as module is checked on. The advantage of adding it to the project is that it would be available for any subsequent debugging, etc.

The contents of the file would be as follows:

clauses
    person("Judith",female()).
        person("Bill",male()).
        person("John",male()).
        person("Pam",female()).
        parent("John","Judith").
        parent("Bill","John").
        parent("Pam","Bill").

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 dynamic 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.

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 person 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).

Now, when you run the program using the Build | Run in the Window menu command, this is what you'll see:

FundamentalVisualProlog8.jpg

The program processes the information in the file fa.txt and works out the logical sequence of the parentages of people given there.

A Round up of the Program

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.

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.

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.

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 backtracking, because the Prolog engine literally seems to backtrack over code which had earlier executed.

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 "fathers" 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.

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.

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).

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's name (in case the name of the offspring was bound) OR the offspring'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.

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.

clauses
    run():-
        console::init(),
        stdIO::write("Load  data\n"),
        reconsult("fa.txt"),
        stdIO::write("\nfather test\n"),
        father(X,Y),
        stdIO::writef("% is the father of %\n", Y, X),
        fail.

Conclusion

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's object-oriented features. A complete console-based application (family1) was developed in this tutorial, which explains, how to create such a program.

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.

References