Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Logic tasks on TurboProlog.doc
Скачиваний:
0
Добавлен:
01.07.2025
Размер:
2.27 Mб
Скачать

  1. At competitions on run John, Pol and Andrew occupied the first three places. What place was occupied with each of them, if Pol has not occupied the second and not the third place and Andrew - not the third one.

/* Solution of this task can be get significantly more simple (see further Turbo Prolog 2), but in this one solution there were using all learning till now Turbo Prolog operators (cut, fail, list, comment, nl, write) to show up that Turbo Prolog let to solve a task with many different approaches.

This task was solved also as example on Visual Prolog. For all students after take decision on Turbo Prolog and form the report. All students will have then to solve appropriate task on Visual Prolog and form other (second) report as test.

For all students! Study this task attentively and try to understand role of each operator. */

Задание.

В процессе выполнения задания была написана программа, позволяющая определить: кто из людей занял какое место. Программа сразу печатает ответ при запуске. Интерфейс Turbo Prolog с введенной программой и полученным результатом представлен на рис.1.

Turbo Prolog 1.

Рисунок 1. Интерфейс программы Turbo Prolog

Текст программы представлен ниже:

domains

strings=string*./*Create List of strings*/

predicates

human(string).

solve(string,string,string).

same(string,string).

member(string,strings).

unique(strings).

clauses

human("John")./*Initialize peoples names*/

human("Andry").

human("Paul").

member(X,[X|_])./*Membership predicate*/

member(X,[_|Y]):-member(X,Y).

unique([]):-!./*Uniqueness check predicate*/

unique([X|Y]):-

member(X,Y),!,fail;

unique(Y).

same(X,X)./*equality check predicate*/

solve(P1,P2,P3):-

human(P1),human(P2),human(P3),

unique([P1,P2,P3]),

not(same(P3,"Andry")),

not(same(P3,"Paul")),

not(same(P2,"Paul")).

goal

solve(P1,P2,P3),write("1 ",P1),nl,

write("2 ",P2),nl,

write("3 ",P3),nl.

В данной программе используются все изученные ранее функции языка Turbo Prolog: списки, рекурсия, предикаты cut и fail. Рекурсия использована для определения принадлежности элемента списку и определения уникальности элементов в списке. Для последнего же использованы предикаты cut и fail.

Заключение

В ходе выполнения данной работы были изучены основы языка Prolog, были применены все навыки, полученные в ходе практических занятий: использование предикатов fail и cut, использование списков и рекурсии. Составленная программа успешно решает задачу определения занятых людьми мест.

Turbo Prolog 2

Solve the following task using Turbo Prolog:

At competition on run John, Paul and Andrew occupied the first three places. What place was occupied with each of them if Paul has not occupied the second and not the third place and Andrew - not the third one.

Solution

To solve the task we wrote a program on Turbo Prolog and run it.

The results we got can be seen on the following screen:

As we can see, John has the third place, Andrew - the second, Paul - the third.

The source code for Turbo Prolog:

domains name=symbol predicates person(name). place(name). accordance(name,name). clauses person(X):- X=john;X=paul;X=andrew. place(X):- X=first;X=second;X=third. accordance(X,Y):- person(X),place(Y),X=paul,not(Y=second),not(Y=third). accordance(X,Y):- person(X),place(Y),X=andrew,not(Y=third),not(accordance(paul,Y)). accordance(X,Y):- person(X),place(Y),X=john,not(accordance(paul,Y)),not(accordance(andrew,Y)).

Conclusion

We wrote the code for Turbo Prolog to solve presented task.

The result we got was the same as the result we got analytically, which proves our code is working correctly

Visual Prolog

Solve the following task using Visual Prolog:

At competition on run John, Paul and Andrew occupied the first three places. What place was occupied with each of them if Paul has not occupied the second and not the third place and Andrew - not the third one.

Solution

To solve the task we wrote a program on Visual Prolog and run it.

The results we got can be seen on the following screen:

As we can see, John has the third place, Andrew - the second, Paul - the third.

The source code for Visual Prolog:

implement main     open core constants     className = "main".     classVersion = "". clauses     classInfo(className, classVersion).      class predicates    place : (string)multi(o) determ.    placement : (string, string) nondeterm (i,o) determ. clauses    place("first").    place("second").    place("third").    placement("paul",X):- place(X), not(X="second"),not(X="third").    placement("andrew",X):- place(X),not(X="third"), not(placement("paul",X)).    placement("john",X):- place(X), not(placement("paul",X)),not(placement("andrew",X)).     clauses    run():-         console::init(),       placement("paul",Y),placement("andrew",Z),placement("john",W),       console::write("Paul had ", Y, " place; Andrew had ", Z, " place; John had ",W," place"),!;         succeed().  end implement main goal     mainExe::run(main::run).

Conclusion

We wrote the code for Visual Prolog to solve presented task.

The result we got was the same as the result we got analytically, which proves our code is working correctly.

  1. Anton and Maxim have surnames Shilov and Gvozdev. What surname has each of them, if Maxim and Shilov live in different houses?

Задание

На языке TurboProlog реализовать решение задачи: Антон и Максим носят фамилии Шилов и Гвоздев. Какую фамилию носит каждый из них, если Максим живут в разных домах?

Описание программы

В процессе выполнения задания была написана программа, которая позволяет определить, какую из фамилий носит каждый из персонажей задачи. Для этого были созданы условия, что Максим не носит фамилию Шилов и Максим не Антон (рисунки 1 и 2).

Рисунок 1. Выполнение программы (часть 1)

Рисунок 2. Выполнение программы (часть 2).

Код программы:

Заключение

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

  1. Three girl-friends went in white, green and dark blue dresses. Kate’s and Anna’s colors of a dress and shoes coincided. Kate’s shoes and dress were not white. Natasha was in green shoes. Determine color of dresses and shoes of each of girlfriends.

  1. At a factory 3 friends work: the mechanic, the turner and the welder. Their surnames are Ivanov, Semenov and Borisov. Mechanic are not has either brothers, or sisters. He is younger from friends. Semenov is married to sister of Borisov and is more senior, than the turner. Name surnames of the mechanic, the turner and the welder.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]