Перпелов / Лб 4
.doc
МІНІСТЕРСТВО ОСВІТИ І НАУКИ, МОЛОДІ ТА СПОРТУ УКРАЇНИ |
||||
ХЕРСОНСЬКИЙ НАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ |
||||
Кафедра інформаційних технологій |
||||
|
||||
ЗВІТ З ЛАБОРАТОРНОЇ РОБОТИ 5 |
||||
|
з дисципліни „Логічне програмування” |
|||
|
студента четвертого курсу денної форми навчання |
|||
|
напряму підготовки 6.050102 “Комп’ютерна інженерія” |
|||
|
з професійною орієнтацією “Комп’ютерні системи та мережі” |
|||
|
галузі знань 0501 “Інформатика та обчислювальна техніка” |
|||
|
факультету кібернетики |
|||
|
Перпелова Сергея |
|||
|
||||
Дата проведення лабораторної роботи: |
|
«10» квітня 2013р. |
||
Дата подання звіту за графіком: |
|
«17» квітня 2013р. |
||
|
|
|
||
Дата подання звіту студентом: |
|
____________________ |
||
Підпис студента: |
|
____________________ |
||
|
|
|
||
Позначка викладача про результати та дату перевірки звіту: |
|
____________________ |
||
|
|
|
||
Відомості про викладача, що виконував перевірку звіту (прізвище, ініціали, посада, науковий ступінь, вчене звання): |
|
Веселовська Г.В., доцент кафедри інформаційних технологій ХНТУ, к.т.н., доцент |
||
|
|
|
||
Підпис викладача, що виконував пере- вірку звіту : |
|
_____________________ |
||
|
||||
Херсон – 2013р. |
ЛАБОРАТОРНА РОБОТА 4
Тема: Синтаксис і семантика мов логічного програмування. Частина 2.
Мета:
1) продовжити практичне знайомство з функціональними можливостями та інструментальними засобами мов логічного програмування;
2) здійснити другий етап практичного опановування наступних понять логічного програмування:
– базового синтаксису та семантики логічних програм;
– особливостей подання та застосування основоположних структур даних;
– особливостей визначення операторів, здійснення обчислень, організації управління ходом виконання програм, введення та виведення інформації в логічних програмах.
Запустіть на виконання та проаналізуйте результати роботи Пролог-програм, наведених у розділі 2 «Основні теоретичні відомості» даних методичних рекомендацій.
% Sheet 1. Program "Input and output of information"
DOMAINS
info = i (string, string, address)
address = a (string, string, integer, integer)
PREDICATES
getinfo (info)
CLAUSES
getinfo (Person):-
write ("Input your information in next format:"), nl,
write ("i (Ivanov, 51-57-31, a (Kherson, Berislav highway, 24, 318))"), nl,
write ("String type information put into the double inverted commas!"), nl, nl,
readterm (info, Person), nl.
GOAL
getinfo (Person), write ("You input next information:"), nl, write (Person), nl.
% Sheet 2_1. Primer 1 of the files input and output (short version)
DOMAINS
file = input; output
GOAL
openread (input, "example.txt"),
readdevice (input),
readln (Str1), write (Str1), nl,
openwrite (output, "result.txt"),
writedevice (output),
readdevice (keyboard),
readln (Str2), write (Str2), nl,
closefile (input),
closefile (output).
% Sheet 2_2.
% Primer 1 of the files input and output (full version with comments)
DOMAINS
file = input; output
GOAL
% відкриття файлу example.txt для читання
openread (input, "example.txt"),
% призначення файлу example.txt пристроєм уведення
% (пристроєм виведення по умовчанню залишається екран)
readdevice (input),
% зчитування з файлу example.txt рядка example в змінну Str1
readln (Str1),
% виведення значення змінної Str1 (рядка example) на екран
write (Str1), nl,
% відкриття файлу result.txt для запису
openwrite (output, "result.txt"),
% призначення файлу result.txt пристроєм виведення
writedevice (output),
% призначення клавіатури пристроєм уведення
readdevice (keyboard),
% зчитування з клавіатури рядка result у змінну Str2
readln (Str2),
% виведення значення змінної Str2 (рядка result) у файл result.txt
write (Str2), nl,
% закриття файлів example.txt і result.txt
closefile (input), closefile (output).
% Sheet 3. Primer 2 of the files input and output
DOMAINS
file = result
PREDICATES
readloop
CLAUSES
readloop:-
readchar (Char),
Char<>'#', !,
write (Char),
readloop.
readloop.
GOAL
openwrite (result, "output.txt"),
writedevice (result),
readloop,
closefile (result).
% Sheet 4. Primer 3 of the files input and output
DOMAINS
file = input; output
PREDICATES
repeat (file)
low2up
CLAUSES
repeat (_).
repeat (File):-
not (eof (File)), repeat (File).
low2up:-
repeat (input),
readln (Str),
upper_lower (UpStr, Str),
write (UpStr), nl,
fail.
low2up.
GOAL
write ("Name of input file: "), readln (Input),
write ("Name of output file: "), readln (Output),
openread (input, Input), readdevice (input),
openwrite (output, Output), writedevice (output),
low2up,
closefile (input), closefile (output).
% Sheet 5. Primer 1 on the processing for strings of symbols
DOMAINS
charlist = char*
PREDICATES
string2charlist (string, charlist)
CLAUSES
string2charlist ("", [ ]):- !.
string2charlist (Str, [H|T]):-
frontchar (Str, H, Str_Rest),
string2charlist (Str_Rest, T).
GOAL
string2charlist ("abcde", List),
write ("List =", List).
% Sheet 6. Primer 2 on the processing for strings of symbols
DOMAINS
charlist = char*
PREDICATES
string2charlist (string, charlist)
CLAUSES
string2charlist (Str, [H|T]):-
frontchar (Str, H, Str_Rest), !,
string2charlist (Str_Rest, T).
string2charlist (_, [ ]).
GOAL
string2charlist ("abcde", List),
write ("List=", List).
% Sheet 7. Primer 1 on the creating and recursive processing for list
DOMAINS
intlist = integer*
PREDICATES
printlist (intlist)
CLAUSES
printlist ([ ]):- !.
printlist ([H | T]):- write (H),
nl,
printlist (T).
GOAL
printlist ([1, 2, 3]).
% Sheet 8. Primer 2_1 on the creating and recursive processing for list
DOMAINS
intlist = integer*
PREDICATES
list_length (intlist, integer)
CLAUSES
list_length ([ ], 0):- !.
list_length (List, Length):-
List = [H | T],
list_length (T, Length_T),
Length = Length_T+1.
GOAL
list_length ([1, 2], Length),
write("Length = ", Length).
% Sheet 9. Primer 2_2 on the creating and recursive processing for list
DOMAINS
intlist = integer*
PREDICATES
list_length (intlist, integer)
CLAUSES
list_length ([ ], 0):- !.
list_length ([H | T], Length):-
list_length (T, Length_T),
Length = Length_T+1.
GOAL
list_length ([1, 2], Length), write("Length = ", Length).
% Sheet 10. Primer 3 on the creating and recursive processing for list
DOMAINS
intlist=integer*
PREDICATES
inverting (intlist, intlist)
processing (integer, integer)
CLAUSES
inverting ([ ], [ ]):- !.
inverting ([H | T], [Inv_H | Inv_T]):-
processing (H, Inv_H),
inverting (T, Inv_T).
processing (0, 0):- !.
processing (H, Inv_H):- Inv_H = -H.
GOAL
inverting ([-2, -1, 0, 1, 2], Inv_List), write("Inv_List = ", Inv_List).
% Sheet 11. Primer 4 on the creating and recursive processing for list
DOMAINS
strlist=string*
PREDICATES
member (string, strlist)
search (string, strlist)
CLAUSES
member (Elem, [Elem | _]):- !.
member (Elem, [_ | T]):-
member (Elem, T).
search (Elem, List):-
member (Elem, List), !,
write ("Element is find !").
search (_, _):- write ("Element dont find !").
GOAL
Cities = ["Kiev", "Odessa", "Kherson", "Nikolaev", "Kahovka"],
City = "Kherson", search (City, Cities).
% Sheet 12. Primer 5 on the creating and recursive processing for list
DOMAINS
intlist=integer*
PREDICATES
append (intlist, intlist, intlist)
CLAUSES
append ([ ], List, List):- !.
append ([H | T], List, [H | App_T]):- append (T, List, App_T).
GOAL
append ([1, 2], [3, 4], App_List), write("App_List = ", App_List).
% Sheet 13. Primer 6 on the creating and recursive processing for list
DOMAINS
integerlist=integer*
PREDICATES
bubble (integerlist, integerlist)
exchange (integerlist, integerlist)
CLAUSES
bubble (List, OrdList):-
exchange(List, TempList), !,
bubble (TempList, OrdList).
bubble (OrdList, OrdList).
exchange ([H1,H2|T], [H2,H1|T]):-
H1 > H2.
exchange ([H|T], [H|T2]):-
exchange (T, T2).
GOAL
bubble ([3,2,1], OrdList),
write("List=", OrdList).
% Sheet 14. Primer 1 on the recursive creating and processing for tree
DOMAINS
treetype = tree (integer, treetype, treetype); nil ()
PREDICATES
print_tree (treetype)
CLAUSES
print_tree (nil):- !.
print_tree (tree(Root, Left, Right)):-
write(Root), nl,
print_tree (Left),
print_tree (Right).
GOAL
print_tree (tree (4, tree (2, tree (1, nil, nil), tree (3, nil, nil)), tree (5, nil, nil))).
% Sheet 15. Primer 2 on the recursive creating and processing for tree
DOMAINS
treetype = tree (integer, treetype, treetype); nil ()
PREDICATES
create (treetype, treetype)
insert (integer, treetype, treetype)
CLAUSES
create (Tree, NewTree):-
readint (New), !,
insert (New, Tree, TmpTree),
create (TmpTree, NewTree).
create (Tree, Tree).
insert (New, nil, tree (New, nil, nil)):- !.
insert (New, tree (Root, Left, Right), tree (Root, NewLeft, Right)):-
New<Root, !,
insert (New, Left, NewLeft).
insert (New, tree (Root, Left, Right), tree (Root, Left, NewRight)):-
insert (New, Right, NewRight).
GOAL
create (nil, Tree),
write (Tree).
% Sheet 16. Primer 3 on the recursive creating and processing for tree
DOMAINS
treetype = tree (integer, treetype, treetype); nil ()
PREDICATES
count2 (treetype, integer, integer)
CLAUSES
count2 (nil, Tmp, Tmp):- !.
count2 (tree (_, Left, Right), Tmp, N):-
NewTmp = Tmp + 1,
count2 (Left, NewTmp, NewTmp2),
count2 (Right, NewTmp2, N).
GOAL
count2 (tree (4, tree (2, tree (1, nil, nil), tree (3, nil, nil)), tree (5, nil, nil)), 0, N),
write (" Number of the tree roots: N = ", N).
Контрольне завдання 2
Підзавдання 2.1. Продемонструйте на декількох наочних прикладах Пролог-програм дію основних стандартних предикатів мови Пролог, призначених для: а) введення та виведення інформації (readint, readreal, readchar, readln, readterm, write, nl); б) файлового введення та виведення інформації (openread, openwrite, openappend, openmodify, readdevice, writedevice, closefile, eof); в) обробки рядків символів (frontchar, fronttoken).
DOMAINS
file = input; output
GOAL
openread (input, "file_in.txt"),
readdevice (input),
readln (Str1),
write (Str1), nl,
openwrite (output, "file_out.txt"),
writedevice (output),
readdevice (keyboard),
readln (Str2),
write (Str2), nl,
closefile (input), closefile (output).