Senin, 07 Desember 2009

TUTORIAL 5 - Summary Chapter 6

INPUT AND OUTPUT in Prolog - Summary Chapter 6

Loops


Introduction

Prolog has no looping facilities, similar effects can be obtained that enable a sequence of goals to be evaluated repeatedly. This can be done in a variety of ways, using backtracking, recursion, built-in predicates, or a combination of these.


6.1 Looping a Fixed Number of Times

No such facility is available in Prolog (directly), but a similar effect can be obtained using recursion, as shown in the example programs below.


Example 1

The following program outputs integers from a specified value down to 1.


loop(0).

loop(N):-N>0,write('The value is: '),write(N),nl,

M is N-1,loop(M).


The loop predicate is defined in terms of itself. The second clause can be thought of as: 'to loop from N, first write the value of N, then subtract one to give M, then loop from M'. This process clearly needs to be terminated and this is achieved by the first clause: 'when the argument is zero, do nothing (and hence stop)'. The first clause can be regarded as a terminating condition for the recursion.


?- loop(6).

The value is: 6

The value is: 5

The value is: 4

The value is: 3

The value is: 2

The value is: 1

yes


Example 2

The next program outputs integers from First to Last inclusive.


/* output integers from First to Last inclusive */

output_values(Last,Last):- write(Last),nl,

write('end of example'),nl.

output_values(First,Last):-First=\=Last,write(First),

nl,N is First+1,output_values(N,Last).


Here output_values has two arguments, which can be read as 'output the integers from First to Last inclusive'. The loop terminates when both arguments are the same.


?- output_values(5,12).

56789

10

11

12

end of example

yes


Example 3

Define a predicate to find the sum of the integers from 1 to N (say for N = 100). It is natural to think of this procedurally, i.e. start with 1, then add 2, then add 3, then add 4, … , then add 100. However the process is much easier to program if reexpressed declaratively in terms of itself.

The sum of the first 100 integers is the sum of the first 99 integers, plus 100.

The sum of the first 99 integers is the sum of the first 98 integers, plus 99.

The sum of the first 98 integers is the sum of the first 97 integers, plus 98.

…………………………………………………………………………….

The sum of the first 3 integers is the sum of the first 2 integers, plus 3.

The sum of the first 2 integers is the sum of the first 1 integers, plus 2.

The sum of the first 1 integers is one.

There are two distinct cases to consider: the general case: 'the sum of the first N integers is the sum of the first N-1 integers, plus N' and the terminating case: 'the sum of the first 1 integers is 1'. This leads directly to the recursive definition:


/* sum the integers from 1 to N (the first argument)

inclusive */

sumto(1,1).

sumto(N,S):-N>1,N1 is N-1,sumto(N1,S1),S is S1+N.


?- sumto(100,N).

N = 5050

?- sumto(1,1).

Yes


Note that using the additional variable N1 for holding the value of N-1 is essential. Writing sumto(N-1,S1) etc. instead would not work correctly. N-1 is a term, not a numerical value.


Example 4

Define a predicate to output the squares of the first N integers, one per line. This can most easily be programmed if first recast in a recursive form, as follows.

To output the squares of the first N integers, output the squares of the first N-1 and then output N2 To output the squares of the first N-1 integers, output the squares of the first N-2 and then output (N-1)2

To output the squares of the first N-2 integers, output the squares of the first N-3 and then output (N-2)2

……………………………………………………………………………………….

To output the squares of the first 3 integers, output the squares of the first 2 and then output 32

To output the squares of the first 2 integers, output the squares of the first 1 and then output 22

To output the squares of the first 1 integers, output the number 1

Here the general case is 'to output the squares of the first N integers, output the squares of the first N-1 and then output N2' and the terminating case is 'to output the squares of the first 1 integers, output the number 1'. This leads to the following two-clause program.


/* output the first N squares, one per line */

writesquares(1):-write(1),nl.

writesquares(N):-N>1,N1 is N-1,writesquares(N1),

Nsq is N*N,write(Nsq),nl.


?- writesquares(6).

149

16

25

36

yes


Example 5

The following program reads the first 6 terms from a specified file and writes them to the current output stream. It uses a 'counting down' method, in a similar way to Example 1.


read_six(Infile):-seeing(S),see(Infile),

process_terms(6),seen,see(S).

process_terms(0).

process_terms(N):-N>0,read(X),write(X),nl,N1 is N-1,

process_terms(N1).


Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4

6.2 Looping Until a Condition Is Satisfied

Many languages have an 'until loop' which enables a set of instructions to be

executed repeatedly until a given condition is met. Again, no such facility is

available directly in Prolog, but a similar effect can be obtained in several ways.

6.2.1 Recursion

Excemple shows the use of recursion to read terms entered by the

user from the keyboard and output them to the screen, until end is encountered

go:-loop(start). /* start is a dummy value used to get

the looping process started.*/

loop(end).

loop(X):-X\=end,write('Type end to end'),read(Word),

write('Input was '),write(Word),nl,loop(Word).

Output

?- go.

Type end to end: university.

Input was university

Type end to end: of.

Input was of

Type end to end: portsmouth.

Input was portsmouth

Type end to end: end.

Input was end

Yes

Using the disjunction operator ;/2 which was defined in Section 4.4 the above

program can be rewritten as a single clause.

loop:-write('Type end to end'),read(Word),

write('Input was '),write(Word),nl,

(Word=end;loop).

Output

?- loop.

Type end to end: university.

Input was university

Type end to end: of.

Input was of

Type end to end: portsmouth.

Input was portsmouth

Type end to end: end.

Input was end

Yes

6.2.2 Using the 'repeat' Predicate

The goal repeat does not repeat anything; it merely succeeds whenever it is called. The great value of repeat is that it also succeeds (as many times as necessary) on backtracking.

This program repeatedly prompts the user to enter a term until either yes or no is entered.

get_answer(Ans):-

write('Enter answer to question'),nl,

repeat,write('answer yes or no'),read(Ans),

valid(Ans),write('Answer is '),write(Ans),nl.

valid(yes). valid(no).

output

?- get_answer(X).

Enter answer to question

answer yes or no: unsure.

answer yes or no: possibly.

answer yes or no: no.

answer is no

X = no

The next program reads a sequence of terms from a specified file and outputs

them to the current output stream until the term end is encountered.

readterms(Infile):-

seeing(S),see(Infile),

repeat,read(X),write(X),nl,X=end,

seen,see(user).

If file myfile.txt contains the lines

'first term'. 'second term'.

'third term'. 'fourth term'.

'fifth term'. 'sixth term'.

'seventh term'.

'eighth term'.

end.

Outout

?- readterms('myfile.txt').

first term

second term

third term

fourth term

fifth term

sixth term

seventh term

eighth term

end

yes

Baik, sekarang saya akan menunjukkan sebuah program Prolog yang digunakan untuk menampilkan sebuah menu, dimana menu ini akan terus keluar tergantung dari masukkan pengguna program. Perintah ‘go’ dalam program, akan menyebabkan program menampilkan menu yang dapat dipilih. Menu ini baru akan tertutup sampai masukkan adalah q (masukkan dapat berbeda-beda program 1 dengan lainnya, tergantung kesepakatan rules di program Prolog). Setiap masukkan harus diikuti dengan tanda titik.
Berikut rules program ini, ketikkan program ini di notepad. Kemudian save dengan tipe file .pl


Pada baris ke-1 terdapat rules ‘go’. Saat Prolog nanti dijalankan, dan anda memasukkan perintah ‘go.’, maka program akan menampilkan tulisan seperti yang telah ditulis di notepad tadi, yaitu “Pemilihan Kegiatan Ekstrakulikuler”, dan sekaligus memanggil method ‘menu’. Dimana method ‘menu’ pada baris ke-2 sudah diatur sehingga ketika method ini dipanggil, ia akan menampilkan teks seperti yang ada di rules diatas, yaitu “PILIH Ekstrakulikuler …dst”. Method menu ini nanti juga akan menyuruh user untuk memasukkan karakter melalui perintah ‘read’, sebagai opsi pilih pengguna program ini nantinya. Ketika pengguna program ini memasukkan karakter a/A, maka program akan menampilkan “Ekstra sepakbola telah anda pilih!” dan sekaligus memanggil method menu kembali. Demikian seterusnya sampai pengguna computer memasukkan karakter ‘q’ (karakter dapat bervariasi dengan program lainnya).
Berikut merupakan contoh program ini ketika dijalankan.


Searching menggunakan method fail di Prolog

Prolog juga menyediakan fitur searching, dimana prolog akan mencari semua property apa yang ingin dicari di database. Misalkan, database menyimpan keterangan bahwa tommy, roodhin, noval adalah murid dan yonatan adalah pekerja. Jika kita ingin mencari semua murid, maka tentu yang akan ditampilkan adalah tommy, roodhin dan Yonatan.
Berikut merupakan contoh program searching, ketikkan program ini di notepad. Kemudian save dengan tipe .pl


Pada baris 1-4 nampak bahwa, program membuat sebuah fakta, bahwa tommy, roodhin dan noval adalah student dan yonatan adalah worker. Bisa dikatakan bahwa database menyimpan keterangan bahwa tommy, roodhin dan noval adalah student dan yonatan adalah worker. Baris 6 nampak bahwa dibuat sebuah rules ‘allstudent’, dimana ketika rules ’allstudent’ dijalankan, akan ditampilkan X dimana X adalah student dan tampilkan juga, “ is a student”. Program akan menampilkan terus menerus setiap student yang ada di database. Jika sudah tidak ada student lagi, maka method fail akan berjalan dan menghentikan program. Jika method allstudent yang kedua / pada baris ke 7 diabaikan, setiap student akan tetap ditemukan, namun akan berakhir dengan kesalahan, akan muncul no setelah hasil ditemukan.
Berikut contoh tampilan ketika program ini dijalankan


Model searching dapat dibuat bervariasi. Berikut merupakan program untuk mencari database yang berisi nama depan, nama belakang, umur, kota asal dan pekerjaan. Program akan menampilkan nama depan dan nama belakang orang yang bekerja sebagai programmer.
Berikut merupakan contoh program. Ketikkan program ini di notepad dan save dengan tipe .pl


Pada baris 1-4 nampak bahwa, program membuat sebuah fakta bahwa, tommy prasetyo, umur 19, kota asal kediri, pekerjaan doktor adalah person, demikian juga noval, roodhin, dan yonatan. Baris ke 6 menyatakan bahwa ‘allprogrammer’ merupakan sebuah method/rules, dimana bila method ini dipanggil, akan menampilkan nama depan (dalam kasus ini saya misalkan karakter X, maksudnya adalah siapapun X itu),nama belakang orang yang bekerja sebagai programmer. Jika di database sudah tidak ada lagi person yang bekerja sebagai programmer, maka program akan berhenti dengan perintah fail.
Berikut contoh program apabila dijalankan:



Searching dapat juga dilakukan tanpa method fail. Sebagai contoh, kita dapat memanipulasi program agar mencari data yang ingin dicari dengan cara menetapkan bahwa program akan berhenti apabila ditemukan m_top.
Berikut contoh programnya, ketikkan program ini dinotepad dan kemudian save dengan tipe .pl


Baris ke 1-4 sama seperti program tadi. Pada baris ke-6 kita membuat sebuah method ‘somepeople’, dimana method ini akan menampilkan nama depan dan belakang ‘person’ yang bekerja sebagai programmer. Program akan berhenti sampai ditemukan nama belakang=m_top, yang tidak lain adalah nama belakang orang terakhir yang bekerja sebagai programmer di database.

Berikut tampilan program bila dijalankan:


Mencari semua daftar kemungkinan

Backtracking dengan failure dapat digunakan juga untuk menemukan kepuasan tujuan yang diinginkan. Misalkan findroute(Town1,Town2,Route) akan digunakan untuk menemukan jarak rute antara dua kota, Town1 dan Town2. Rincian dari rules ini tidak relevan. Rincian tersebut akan diartikan Town1 dan Town2 adalah kota dan Route adalah daftar. Backtracking dengan failure dapat digunakan untuk mencari semua kemungkinan rute antara kota 1 dan kota 2.
Berikut contoh programnya, ketikkan di notepad dan save dengan tipe .pl



Berikut tampilan program bila dijalankan:




Tidak ada komentar:

Posting Komentar