Wednesday, December 9, 2009
Looping in Prolog
Sebagian besar bahasa pemrograman mempunyai fasilitas looping. Akan tetapi, fasilitas ini tidak terdapat di prolog. Sebagai penggantinya, kita dapat menggunakan backtracking, rekursi, built-in predikat, atau mengkomninasikannya.
Looping a Fixed Number of Times
Dalam prolog tidak ada fasilitas ‘for loops’ sebagaimana bahasa pemrograman lain. Sebagai penggantinya, kita dapat menggunakan rekursi.
Contoh :
Program ini mengeluarkan bilangan bulat mulai dari angka yang dimasukkan hingga 1.
Notepad :
loop(0).
loop(N):-N>0,write('The value is: '),write(N),nl,
M is N-1,loop(M).
Prolog :
?- 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
Looping Until a Condition Is Satisfied
Dalam prolog tidak ada fasilitas ‘until loops’ sebagaimana bahasa pemrograman lain. Sebagai penggantinya, kita dapat menggunakan :
1. Rekursi
Contoh :
Notepad :
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).
Prolog :
?- 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
2. ‘Repeat’ predikat
Contoh :
Notepad :
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).
Prolog :
?- 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
Backtracking with Failure
Berikut adalah fungsi-fungsi backtracking dalam prolog.
1. Mencari database prolog
Contoh :
Notepad :
dog(fido).
dog(fred).
dog(jonathan).
alldogs:-dog(X),write(X),write(' is a dog'),nl,fail.
alldogs.
Prolog :
?-alldogs
fido is a dog
fred is a dog
jonathan is a dog
yes
2. Menemukan solusi ganda
Contoh :
find_all_routes(Town1,Town2):-
findroute(Town1,Town2,Route),
write('Possible route: '),write(Route),nl,fail.
find_all_routes(_,_).
Wednesday, November 25, 2009
INPUT and OUTPUT in Prolog
Outputting Terms
Output form that be used in prolog is write/1 dan nl/0 predicate. Evaluating the predicate write/1 causes the term to be written to the current output stream and evaluating a nl goal causes a new line to be output to the current output stream.
Examples :
?- write('Example of use of nl'),nl,nl,write('end of example'),nl.
Example of use of nl
end of example
yes
if we want to show atoms, we can use writeq/1.
Examples :
?- writeq('a string of characters'),nl.
'a string of characters'
yes
Inputting Terms
Input form that be used in prolog is read/1. Evaluating it causes the next term to be read from the current input stream. In the input stream, the term must be followed by a dot ('.') and at least one white space character, such as space or newline. The dot and white space characters are read in but are not considered part of the term.
Example :
?- read(Z).
: [a,b,mypred(p,q,r),[z,y,x]].
Z = [a,b,mypred(p,q,r),[z,y,x]]
?- read(Y).
: 'a string of characters'.
Y = 'a string of characters'
?- X=fred,read(X).
: jim.
no
?- X=fred,read(X).
: fred.
X = fred
Input and Output Using Characters
There are many characters that can be used in input and output using prolog. All printing characters and many non-printing characters have a corresponding ASCII (American Standard Code for Information Interchange) value, which is an integer from 0 to 255.
The table below gives the numerical ASCII values corresponding to the main printable characters and some others.
9 : tab
10 : end of record
32 : space
33 : !
34 : "
35 : #
36 : $
37 : %
38 : &
39 : '
40 : (
41 : )
42 : *
43 : +
44 : ,
45 : -
46 : .
47 : /
48-57 : 0 to 9
58 : :
59 : ;
60 : <
61 : =
62 : >
63 : ?
64 : @
65 : -
90 : A to Z
91 : [
92 : \
93 : ]
94 : ^
95 : _
96 : `
97 : -
122 : a to z
123 :{
124 : |
125 : }
126 : ~
Characters whose ASCII value is less than or equal to 32 are known as white space characters.
Outputting Characters
Predicate that be used for output characters is put/1 which must be a number from 0 to 255 or an expression that evaluates to an integer in that range. Evaluating a put goal causes a single character to be output to the current
output stream.
Example :
?- put(97),nl.
a
Inputting Characters
Predicate that be used for input a single character are get0/1 and get/1. Evaluating a get0 goal causes a character to be read from the current input stream and evaluating a get goal causes the next non-white-space character to be read from the current input stream.
Example :
?- get0(N).
: a
N = 97
?- M is 41,get0(M).
: )
M = 41
?- M=dog,get0(M).
: )
No
?- get(X).
: Z
X = 90
Using Characters: Examples
The predicate readin is defined recursively. It causes a single character to be input and variable X to be bound to its ASCII value. The action taken (the process(X) goal) depends on whether or not X has the value 42 signifying a * character. If it has, the evaluation of the goal stops. If not, the value of X is output, followed by a new line, followed by a further call to readin. This process goes on indefinitely until a * character is read.
Example :
readin:-get0(X),process(X).
process(42).
process(X):-X=\=42,write(X),nl,readin.
?- readin.
: Prolog Example*
80
114
111
108
111
103
32
69
120
97
109
112
108
101
yes
The ASCII values of the input characters are not output, but the number of characters (excluding the *) is output.
The count predicate is defined with two arguments which can be read as 'the number of characters counted so far' and 'the total number of characters before the *'.
Example :
go(Total):-count(0,Total).
count(Oldcount,Result):-
get0(X),process(X,Oldcount,Result).
process(42,Oldcount,Oldcount).
process(X,Oldcount,Result):-
X=\=42,New is Oldcount+1,count(New,Result).
?- go(T).
: The time has come the walrus said*
T = 33
?- go(T).
: *
T = 0
Predicate vowel tests for one of the 10 possible vowels (five upper case and five lower case), using their ASCII values.
go(Vowels):-count(0,Vowels).
count(Oldvowels,Totvowels):-
get0(X),process(X,Oldvowels,Totvowels).
process(42,Oldvowels,Oldvowels).
process(X,Oldvowels,Totalvowels):-
X=\=42,processChar(X,Oldvowels,New),
count(New,Totalvowels).
processChar(X,Oldvowels,New):-vowel(X),
New is Oldvowels+1.
processChar(X,Oldvowels,Oldvowels).
vowel(65). /* A */
vowel(69). /* E */
vowel(73). /* I */
vowel(79). /* O */
vowel(85). /* U */
vowel(97). /* a */
vowel(101). /* e */
vowel(105). /* i */
vowel(111). /* o */
vowel(117). /* u */
?- go(Vowels).
: In the beginning was the word*
Vowels = 8
?- go(Vowels).
: pqrst*
Vowels = 0
Input and Output Using File
Prolog doing input and output in current stream form. The user may open and close input and output streams with any number of named files but there can only be one current input and output stream.
File Output: Changing the Current Output Stream
The current output stream can be changed using the tell/1 predicate. This value can be restored either by using the told/0 predicate or by tell(user).
File Input: Changing the Current Input Stream
The current input stream can be changed using the see/1 predicate which representing a file name, e.g. see('myfile.txt'). This value can be restored either by using the seen predicate or by see(user).
1. Reading from Files: End of File
If the end of file is encountered when evaluating the goal read(X), variable X will be bound to the atom end_of_file. If the end of file is encountered while evaluating the goal get(X) or get0(X), variable X will be bound to a 'special' numerical value.
2. Reading from Files: End of Record
Typically the end of a line of input at the user's terminal will be indicated by the character with ASCII value 13. The end of a record in a file will generally be indicated by two ASCII values: 13 followed by 10.
readline:-get0(X),process(X).
process(13).
process(X):-X=\=13,put(X),nl,readline.
?- readline.
: Prolog test
P
r
o
l
o
g
t
e
s
t
yes
Friday, November 13, 2009
Operator and Arithmetic
Practical Exercise 4
(1) This program is based on Animals Program 3, given in Chapter 2.
dog(fido). large(fido).
cat(mary). large(mary).
dog(rover). small(rover).
cat(jane). small(jane).
dog(tom). small(tom).
cat(harry).
dog(fred). large(fred).
cat(henry). large(henry).
cat(bill).
cat(steve). large(steve).
large(jim).
large(mike).
large_dog(X):- dog(X),large(X).
small_animal(A):- dog(A),small(A).
small_animal(B):- cat(B),small(B).
chases(X,Y):-
large_dog(X),small_animal(Y),
write(X),write(' chases '),write(Y),nl.
Convert the seven predicates used to operator form and test your revised program.
The output should be the same as the output from the program above. Include
directives to define the operators in your program.
(2) Define and test a predicate which takes two arguments, both numbers, and
calculates and outputs the following values: (a) their average, (b) the square root of
their product and (c) the larger of (a) and (b).
We make tutorial for number 1 in Engkish and number 2 in Bahasa Indonesia. But we aren't write our tutorial about this problem on this page. You can download it by clicking this FILE!!!
Operators and Arithmetics in Prolog
Operators
Up to now, Prolog user usually use the notation for predicates by a number of arguments in parentheses.
Ex : likes(john,mary)
There is another alternative :
- Two arguments (a binary predicates) be converted to an infix operator
the functor be written between two arguments with no parentheses
Ex : john likes mary
- One argument (a unary predicate) be converted to :
1. Prefix operator the functor be written before the argument with no parentheses
Ex : isa_dog fred
2. Postfix operator the functor be written after the argument
Ex : fred isa_dog
Both of predicate (one or two arguments) can be converted to an operator by entering a goal using the op predicate at the system prompt. Ex :
?-op(150,xfy,likes).
This predicate takes three arguments :
1. 150 (operator precedence) : an integer from 0 upwards
So we can change it with another integer.
2. Xfy : the predicate is binary and is to be converted to an infix operator.
This argument should normally be one of the following three atoms:
1. Xfy
2. Fy : the predicate is unary and is to be converted to an prefix operator
3. Xf : the predicate is unary and is to be converted to a postfix operator
3. Likes : the name of the predicate that is to be converted to an operator.
Arithmetics
Prolog user can doing arithmetic calculate with prolog, such as :
1. Arithmetic operator
X+Y : sum of X and Y
X-Y : dfference of X and Y
X*Y : product of X and Y
X/Y : quotient of X and Y
X//Y : the ‘integer quotient’ of X and Y (the result is truncated to the nearest integerbetween it and zero)
X^Y : X to the power of Y
-X : negative of X
abs(X) : absolute value of X
sin(X) : sine of X
cos(X) : cosine of X
max(X,Y) : yhe larger of X and Y
sqrt(X) : square root of X
2. Operator presedence in arithmetic expression
Prolog use ordinary algebra algorithm in arithmetic operation.
Ex : A+B*C-D
In the algebra, C*B are calculate first, then the result+A, then the result of sum-D. it is same with those in prolog. But, if we want to calculate A+B, C-D, then multiply both of the result, we must add the parentheses.
Ex : (A+B)*(C-D)
3. Relasion operator
The operator like =,!=, >, >=, <, <= can be used in prolog
Degree operator
Under is the rist of equality operators that used in prolog with the function of each operator:
• Arithmetic Expression Equality ( =:= )
• Arithmetic Expression Inequality ( =\= )
• Terms Identical ( == )
• Terms Not Identical ( \== )
• Terms Identical With Unification ( = )
• Non-Unification Between Two Terms( \= )
Logic operator
a. Operator NOT
Operator not can be placed before predicate to give the negation. Predicate that be negation has the truth value if the origin predicate is false and has the false value if the origin predicate is truth.
The example of using operator not :
dog(fido).
?- not dog(fido).
no
?- dog(fred).
no
?- not dog(fred).
Yes
b. Disjunction operator
Disjunction operator is used as operator ‘atau’.
Ex :
?- 6<3;7 is 5+2.
yes
?- 6*6=:=36;10=8+3.
yes
Wednesday, October 21, 2009
Fact, Rules, Predicate, and Variable in Prolog
(1) Type the following program into a file and load it into Prolog.
/* Animals Database */
animal(mammal,tiger,carnivore,stripes).
animal(mammal,hyena,carnivore,ugly).
animal(mammal,lion,carnivore,mane).
animal(mammal,zebra,herbivore,stripes).
animal(bird,eagle,carnivore,large).
animal(bird,sparrow,scavenger,small).
animal(reptile,lizard,scavenger,small).
Devise and test goals to find (a) all the mammals, (b) all the carnivores that are mammals, (c) all the mammals with stripes, (d) whether there is a reptile that has a
mane.
(2) Type the following program into a file
/* Dating Agency Database */
person(bill,male).
person(george,male).
person(alfred,male).
person(carol,female).
person(margaret,female).
Extend the program with a rule that defines a predicate couple with two arguments, the first being the name of a man and the second the name of a woman.
Load your revised program into Prolog and test it.
To solve those problem, please do this step. Check this out!
First Question
1. Type all words in the box in Notepad, save it and don’t forget to insert .pl at the end of your name.
2. Consult your saved file in PROLOG.
3. To find the answer of number 1.a, you must type this.
?- animal(mammal,X,_,_).
Then press Enter.
4. To find another answers, type ; then another answers can appear until word No appears. It means there is no answer again.
5. To find the answer of number 1.b, you must type this.
?- animal(mammal,Y,carnivore,_).
Then press Enter.
6. To find another answer, follow the instruction number 4.
7. To find the answer of number 1.c, you must type this.
?- animal(mammal,Z,_,stripes).
Then press Enter.
8. To find another answer, follow the instruction number 4.
9. To find the answer of number 1.d, you must type this.
?- animal(reptile,R,_,mane).
Then press Enter.
10. Oh, what happened with this answer? Is there a wrong step? Absolutely no, because there is no reptile has mane in that program.
Second Question
1. Type all words in the box in Notepad.
2. We must make a rule to find all possible couples. The couple must a man and a woman, not both of them are men or women. So the correct rule for this problem is :
couple(X,Y) :- person(X,male),person(Y,female).
3. Type it and save but don’t forget to insert .pl at the end of your name.
4. Consult your saved file in PROLOG.
5. To find the answer, type this
?- couple(X,Y).
Then press Enter.
6. To find another answers, type ( ; ) then another answers can appear until word No appears. It means there is no answer again.
To make it clearly, please click this FILE!!!
Tuesday, October 13, 2009
How to list all possible combination (consisting two elements) of a set in PROLOG and capture the image from PROLOG
The most wellknown on mathemathics lesson is sets. What is sets? Sets is a collection of well-defined object.
To definite subset operation, we will begin with definite a new predicate sis/2.
- Firstly,write op(710,xfx,sis). On SWI-prolog then press enter .
- Second, Write op(200,yfx,and). Then press enter
- Write again op(200,yfx,or). Then press enter
We don’t need to definite the minus operator for difference because its already been definited.
Now we need the definition from and, or, and – when we using sis connector. We use findall/3 predicate. Write on the notepad then save with format .pl
Example : lap.pl

This is used to find all of element’s member that same from A and B sets, all of member on A or B sets, and all of member in A but not exist in B.
Then, on the prolog, we consult the data that has been saved. File – Consult – lap.pl. then press enter.
Now,we write the member of sets on prolog, then follow the instruction A sis F and M, so do for or and –
Example : F=[acer,toshiba,dell.apple],M=[dell,apple,fujitsu]. Then press enter. so do for Or and –

Now, we are trying to combine chance from two sets. Here, example of chance from two sets about laptop and operation system.
- Write the member of sets on notepad, then save with .pl format

- Open swi-prolog program, choose File - consult – choose our data .pl

- On prolog, write laptop(X),operationsystem(Y). And don’t forget to give .(dot/titik) on the last sentence.Then press enter.
- Then will appear the first chance. Then press ( ; ) until the last chance appear and NO also appeared.

That’s all the way to combine two sets on prolog. Actually this is very easy if we want to try it and do more practice. FIGHTING!!!
^_^
For make it clearly, please click this file!