Основы Системы Visual Prolog: различия между версиями

Материал из wikiru.visual-prolog.com

Строка 86: Строка 86:
====Goal (цель)====
====Goal (цель)====


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


Для того, чтобы это стало возможным, введен специальный раздел, обозначенный ключевым словом ''Goal''. Его можно представлять как особый предикат, не имеющий аргументов. Это предикат - именно тот предикат, с которого вся программа начинает исполняться.
Для того, чтобы это стало возможным, введен специальный раздел, обозначенный ключевым словом ''Goal''. Его можно представлять как особый предикат, не имеющий аргументов. Это предикат - именно тот предикат, с которого вся программа начинает исполняться.

Версия 16:21, 20 ноября 2007

Основы 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, повышается конечная эффективность программиста. Программист не должен ждать, когда реально работаящая программа совершит ошибку. Действительно, те из Вас, кто имеет опыт в программировании, понимает насколько этот код безопасен. Часто конкретная последовательность событий, приводящая к исключению периода исполнения кажется настолько неуловимой, что ошибка может проявиться через много лет, или она может заявить о себе в критической ситуации и привести к непредсказуемым последствиям!

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

Ключевые слова

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

Исключением из этого правила являются ключевые слова implement и end implement. Код, содержащийся между этими ключевыми словами, есть код, который относится к конкретному классу. Те, кто не понимает концепцию класса, может пока (в рамках этого руководства) представлять себе его как модуль или раздел какой-то программы более высокого уровня.

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

В этом руководстве используются следующие ключевые слова:

implement и end implement

Среди всех ключевых слов, обсуждаемых здесь, это единственные ключевые слова, используемые парно. Visual Prolog рассматривает код, помещенный между этими ключевыми словами, как код, принадлежащий одному классу. За ключевым словом implement обязательно ДОЛЖНО следовать имя класса.

open

Это ключевое слово используется для расширения области видимости класса. Оно должно быть помещено вначале кода класса, сразу после ключевого слова implement (с именем класса и, возможно именем интерфейса - прим. перев.).

constants

Это ключевое слово исползуется для обозначения секции кода, котора определяет неоднократно используемые значения, применяемые в коде. Например, если строковый литерал "PDC Prolog" предполагается использовать в различных местах кода, тогда можно единожды определить мнемоническое (краткое, легко запоминаемое слово) для использовани в таких местах:

constants
pdc="PDC Prolog".

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

domains

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

Вообще говоря, объявляется функтор, который будет использоваться в качестве домена и ряд доменов, которые используются в качестве его аргументов. Функторы и составные домены рассматриваются в соответствующем руководстве.

class facts

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

class predicates

Эта секция содержит объявления предикатов, которые определяются в тексте программы в разделе clauses. И опять, объявление предиката - это имя, которое присваивается предикату, и набор аргументов, каждый из которых должен соответствовать либо стандартному (предопределенному), либо объявленному домену.

clauses

Среди всех разделов, существующих в тексте программ на Visual Prolog, это единственный раздел, который близко совпадает с традиционными программами на Прологе. Он содержит конкретные определения объявленных в разделе class predicates предикатов, причем синтаксически им соответствующие.

goal

Этот раздел определяет главную точку входа в программу на языке системы Visual Prolog. Более детальное описание приводится ниже.

Goal (цель)

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

Для того, чтобы это стало возможным, введен специальный раздел, обозначенный ключевым словом Goal. Его можно представлять как особый предикат, не имеющий аргументов. Это предикат - именно тот предикат, с которого вся программа начинает исполняться.

Файловое структурирование программ

Необходимость помещения всех частей большой программы в один файл несомненно является неудобством. Это ведет к тому, что программа становится нечитаемой и иногда неправильной. Visual Prolog предусматривает возможность деления текста программы на отдельные файлы, используя среду IDE (Integrated Development Environment) и, кроме того, IDE позволяет помещать логически связанные фрагменты текста программы в отдельные файлы. Несмотря на такое разделение программы на части, сущности, находящиеся в общем использовании, доступны.

Например, если имеется домен, который используется несколькими файлами, то объявление домена делается в отдельном файле и к этому файлу из других файлов существует доступ.

Для упрощения этого руководства мы будем использовать один файл для разработки текста программы. На самом деле в процессе построения программы среда IDE создавала бы автоматически несколько файлов, но мы сейчас будем это умалчивать. Об этом написано в других руководствах.

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