We are NOT MAD! but we are Member At Discrete Math C….

INPUT and OUTPUT in Prolog ch.3

Posted by madmathc pada Desember 22, 2009

This is the last post of this session….

(4) Example I make this file..

And the second file …

Next, type this rule… and save it in .pl

Consult it in Prolog. Then type this..


The result is..

Just it? No, look at your computer. You will find file with name out1.txt. Open it and look…

(5) You can try to type this. Save it in test1.txt

Next type this and save in test2.txt

Type this rule and save it in compare.plThen, consult it in PROLOG. Next type this…


Then the result is….

Finally, this chapter have finished. Thanx for coming… Don’t forget to give a comment.:-)

Ditulis dalam Tutorial | Leave a Comment »

INPUT and OUTPUT in Prolog ch.2

Posted by madmathc pada Desember 22, 2009

Now we continue to explain other numbers in Practical Exercise INPUT and OUTPUT in Prolog

(2) First, type this in notepadand save it.

Then type this to make rule for Prolog. Save it ang don’t forget to add .pl at the end of your filename.

Next consult it. After that, type this…


and press Enter

Then automatically out.txt appears… Open it. This is the layout…

(3) Type it in testa.txt

Type this rule. Save it and give name

After that, consult it. Next type this…


Then the output is

This session will be continued at next post. thank for coming…:-)

Ditulis dalam Tutorial | Leave a Comment »


Posted by madmathc pada Desember 22, 2009

Huff… so long I didn’t write at this blog because many assignments must be done and because these two weeks is the final week of 1st semester, projects and final test are coming to me. T.T….But now it is time for me to show u how to finish Practical Exercise in chapter INPUT & OUTPUT. These are the question :

(1) Define a predicate makelower/0 which reads in a line of characters from the keyboard and outputs it again as a single line with any upper case letters converted to lower case. (The ASCII values of the characters a, z, A and Z are 97, 122, 65 and 90, respectively.)

Thus the following would be a typical use of makelower:

?- makelower.

: This is an Example 123 inCLUDing numbers and symbols +-*/@[] XYz

this is an example 123 including numbers and symbols +-*/@[] xyz


(2) Define a predicate copyterms which reads all the terms in a text file and outputs them as terms to another text file one by one on separate lines. The output file should be in a format suitable for use as the input file in a subsequent call of copyterms. Thus for example if the input file contained

‘first term’. ‘second term’.

‘third term’.

fourth. ‘fifth term’.


The output file would contain

first term’.

‘second term’.

‘third term’.


‘fifth term’.


(3) Create a text file testa.txt containing two lines, each of five characters followed by a new line, e.g.



Define a predicate readfile that will read fifteen characters from this file one by one and output the ASCII value of each character. Use this to establish whether the representations of ‘end of file’ and ‘end of record’ for your version of Prolog are as suggested in Sections 5.9.1 and 5.9.2, respectively.

(4) Using a text editor, create two text files in1.txt and in2.txt, each comprising a number of terms terminated by end. Define and test a predicate combine that takes the names of two input files as its first two arguments and the name of an output file as its third argument. The output file should contain the terms in the first input file followed by the terms in the second, one per line and terminated by end.

(5) Define and test a predicate compare that reads in two text files term by term and for each pair of corresponding terms outputs a message either saying that they are the same or that they are different. Assume that both files contain the same number of terms and that the final term in each is end.

And now the solution of those problem are…..

(1) Type this in notepad and save. Don’t forget to add .pl at the end of your filename.


Then consult on Prolog.

makelower2After that, type

This is an Example 123 inCLUDing numbers and symbols +-*/@[] XYz

then press Enter. The output shoud be here

makelower2For next number, they will be posted soon. Thank u.

Ditulis dalam Tutorial | Leave a Comment »

Simple Expert System on Prolog “Rubik’s Cube Puzzle”

Posted by madmathc pada Desember 10, 2009

@Mo2nCha’09 et all

1. What is a Rubik’s cube and what’s the problem? ( Apa sih kubus Rubik dan apa yang menjadi masalahnya?)

Rubik’s cube is a simple looking puzzle. It is a cube with nine tiles on each face. In its solved state each of the sides is made up of tiles of the same color, with a different color for each side. Each of the tiles is actually part of a small cube, or cubie. Each face of the cube (made up of nine cubies) can be rotated. The mechanical genius of the puzzle is that the same cubie can be rotated from multiple sides. A corner cubie can move with three sides, and edge cubie moves with two sides. Figure below shows a cube in the initial solved state, and after the right side was rotated 90 degrees clockwise. Then the problem is to take a cube whose sides have been randomly rotated and figure out how to get it back to the initial solved state. The scrambled cube might look like that of figure below.

The problem is, there are an astronomical number of possible ways to try to unscramble the cube, not very many of which lead to the solved state. To reach a solution using a blind search algorithm is not feasible, even on the largest machines. A human expert can unscramble the cube in well less than a minute. The difficulty with solving the cube revolves around the fact that if you move one cubie, you have to move seven other cubies as well (the center one doesn’t really go anywhere). This is not a big problem in the early stages of unscrambling the cube, but once a number of tiles are positioned correctly, new rotations tend to destroy the solved parts of the cube. The experienced cube solver knows of complex sequences of moves which can be used to manipulate a small portion of the cube without disturbing the other portions of the cube. For example a 14 move sequence can be used to twist two corner pieces without disturbing any other pieces.It is important to realize there are actually two different senses of solving the cube. One assumes the problem solver has no previous knowledge of the cube. The other assumes the individual is an expert familiar with all of the intricacies of the cube. In the first case, the person solving the cube must be able to discover the need for complex sequences of moves and then discover the actual sequences. The program does not have anywhere near the level of “intelligence” necessary to solve the cube in this sense.In the second case the person is armed with full knowledge of many complex sequences of moves which can be brought to bear on rearranging various parts of the cube. The problem here is to be able to quickly determine which sequences to apply given a particular scrambled cube. This is the type of “expertise” which is contained in the Rubik’s cube program. In the following sections we will look at how the cube is represented, what is done by searching, what is done with heuristics, how the heuristics are coded, how the cube is manipulated, and how it is displayed.

As we could say in Bahasa, permasalahan yang ada pada kubus rubik adalah bagaimana mengacak sebuah rubik kubus yang teratur dengan memutar 90 derajat searah jarum jam menjadi sebuah susunan kubus yang acak, kemudian dari posisi dan susunan yang acak tersebut dikembalikan kepada susunan semula (teratur), seorang ahli puzzle kubus bisa saja memecahkan masalah tersebut hanya dalam hitungan menit, tapi buat orang awam mencari susunan yang tepat untuk satu sisi kubus bisa memecah formasi sisi lainnya, dalam asumsi penyelesaiannya ada dua tipe asumsi orang yang dapat menyelesaikan, satu adalah seorang yang awam tentang puzzle kubus yang kedua memang seorang tersebut sudah ahli didalamnya. Sekarang bagaimana menggunakan aplikasi Prolog agar urutan penyelesaiannya bisa cepat, meskipun sebuah program tidak memiliki indera tertentu untuk menyelesaikan puzzle ini.

2. Modelling Rubik’s Cube

The Standard cube has 5.7 cm ribs, Puzzle has 26 miniature cubes on the surface. Center of each cube surface is the main box position has remained a central mechanism. With structure, the small cubes can be played. The remaining 21 pieces of the cube that can be changed its position while the other 6 as The main axis is fixed but still can rotated. Normal Rubik’s cube (3x3x3) has (8! × 38-1) × (12! × 212-1) / 2 = different positions (permutations). Based on the size of the position all cubes can be solved with 27 steps or less. If every permutation attempted 1 by one it will take 261 years light. And if the surface of the cube of each permutasinya spread will be proportional with 256 times the size of the earth In fact there are (8! × 38) × (12! × 212) = 519. possibilities compilation of each piece to build this cube, but 1 in 12 that can be achieved. This is because there are no steps to do sequence so as to exchange a pair of or rotate pieces contained in the corner. Rubik’s cube can be represented as a finite state machine and receive language like any other machine. Language accepted composed of strings of each step. Even so, many of the assumptions the status of this machine enormous. This causes the process status of the search space is very difficult to do except that most likely removed at the time of checking. This machine can be modeled with a focus to the small boxes that build koyal big. Small boxes are also a finite state machines that accept languages certain. All slices of the language accepted by setipa small box is the language accepted by a large box.

Or in Bahasa we could say that : Kubus standar memiliki ukuran rusuk 5.7cm. Puzzle memiliki 26 miniatur kubus padapermukaannya. Kubus pusat dari setiap permukaannya adalah kotak utama yang posisinya sudah tetap sebagai mekanisme pusat. Dengan struktur tersebut, kubus-kubus kecil lainnya dapat diputar. Tersisa 21 potongan kubus yang dapat diubah posisinya sedangkan 6 lainnya sebagaisumbu utama yang tetap tetapi tetap dapat dirotasikan. Rubik’s cube normal (3x3x3) memiliki (8! × 38−1) × (12! × 212−1)/2 = posisi berbeda(permutasi). Berdasarkan besarnya jmlah posisi tersebut, semua kubus dapat dipecahkan dengan 27 langkah atau kurang. Jika setiap permutasi dicoba 1 per satu maka akan membutuhkan waktu 261 tahun cahaya (aji gilee…selama itukah?!) Dan apabila permukaan kubus dari setiap permutasinya dibentangkan maka akan sebanding dengan 256 kali luas bumi Faktanya terdapat (8! × 38) × (12! × 212) = 519. kemungkinan penyusunan dari setiap potongan untuk membangun kubus ini, tapi 1 diantara 12 yang dapat dicapai. Hal ini dikarenakan tidak ada langkah yang dilakukan secara berurutan sehingga dapat menukar sepasang atau merotasikan potongan yang terdapat di pojok. Rubik’s cube dapat direpresentasikan sebagai mesin status terhingga dan menerima bahasa seperti mesin lainnya. Bahasa yang diterima tersusun atas string setiap langkah. Walau begitu, banyaknya status yang menjadi asumsi mesin ini sangatlah besar. Hal ini menyebabkan proses pencarian ruang statusnya sangat sulit dilakukan kecuali jika sebagian besar kemungkinan dihilangkan pada saat pengecekan.
Mesin ini dapat dimodelkan dengan fokus kepada kotak-kotak kecil yang membangun koyal besar. Kotak-kotak kecil tersebut juga merupakan mesin status berhingga yang menerima bahasa tertentu. Semua irisan dari bahasa yang diterima oleh setiap kotak kecil adalah bahasa yang diterima oleh kotak besar

The core of the program has to be the knowledge representation of the cube and its fundamental rotations. The cube lends itself to two obvious representation strategies. It can either be viewed simply as 54 tiles, or as 20 cubies (or pieces) each with either two or three tiles. Since much of the intelligence in the program is based on locating pieces and their positions on the cube, a representation which preserves the piece identity is preferred. However there are also brute force search predicates which need a representation which can be manipulated fast. For these predicates a simple flat structure of tiles is best. The next decision is whether to use flat Prolog data structures (terms) with each tile represented as an argument of the term, or lists with each element a tile. Lists are much better for any predicates which might want to search for specific pieces, but they are slower to manipulate as a single entity. Data structures are more difficult to tear apart argument by argument, but are much more efficient to handle as a whole. By using fixed length records, some Prologs use lists internally thus changing the performance trade-offs mentioned.

*the phrase  “hidden”  is the part that cant be viewed when we look the cube from the front

The tabel above mentioning about 4 basic types of pieces cube different. Corner cube, cube ribs, the middle cube (on each surface), and the center cube is not visible from the outside. As a convention, the middle cube hasa fixed position (though can be rotated). This meant that every other piece of the cube still can be moved without having to go move the cube center. In fact, the cube center always the same when direlasikan with others. Consider each cube was fixed can be symbolized as the direction. Each piece of the cube has 6 sides. If we move the pieces of the available cube
of the whole cube (), we can find 6 side of the cube and identify colors indicates the direction of what. This information can be used to define the status of a cube pieces with the following examples:

mc(Front,Top,Left,Hidden,Bot,Right) atau mc(F,T,L,H,B,R)

Where each argument has a meaning: green (g), white (w),  orange (o), yellow (Y), blue (b), red (r), none (n). Suppose Instantiation of the cube pieces first as mc (n, n, o, y, b, n). This means under the front-facing surfaces are considered no color (or “none”), the top also “None”, the left side of orange, part “Hidden” is yellow, bottom color blue, the right is “none”. (This initiation produce the first piece of the cube as position found). The result of all this is that we do not need to describe the status of the color on every surface: we can solve cube pieces as small cubes for later recorded orientation. For example, the first piece of cube can be positioned with the color orange as front. But we also need to know orientation to know their status. At side in front of orange, yellow sides will facing up, right, bottom or left. Within other words cut the cube has a total of 24 pieces status .

cube(X1, X2, X3, X4, ………., X53, X54).%this representing the cube structure

[p(X1), p(X2), ...p(X7, X8, X9), ...p(X31, X32), p(X33, X34), ...]. %where each X represents a tile, or by the list, where each p(..) represents a piece. A piece might have one, two, or three arguments depending on whether or not it is a center piece, edge piece, or corner piece.

goalstate( cube(‘F’, ‘R’, ‘U’, ‘B’, …………)). % The tiles are each represented by an uppercase letter representing the side of the cube the tile should reside on. These are front, back, top, bottom, right, and left. (The display routine maps the sides to colors.) Quotes are used to indicate the tiles are constants, not variables. Using the constants, the solved state (or goal state of the program) is stored as the Prolog fact goalstate/1

Having decided on two representations, it is necessary to quickly change from one to the other. Unification has exactly the power we need to easily transform between one notation of the cube and the other. A predicate pieces takes the flat structure and converts it to a list.

pieces( cube(X1, X2, ……. X54), [p(X1), ......p(X7, X8, X9), .....]).

If Z is a variable containing a cube in structure notation, then the query: ?- pieces(Z, Y). %Will bind the variable Y to the same cube in list notation. It can also be used the other way.

The following query can be used to get the goal state in list notation in the variable PieceState:

?- goalstate(FlatState), pieces(FlatState, PieceState).
FlatState = cube(‘F’, ‘R’, ‘U’, ‘B’, ……).
PieceState = [p('F'), p('R'), ....p('R', 'U'),....p('B', 'R', 'F'), ....]. %
The first goal unifies FlatState with the initial cube we saw earlier. pieces/2 is then used to generate PieceState from FlatState.

3. Rotation (Perputaran)

Unification also gives us the most efficient way to rotate a cube. Each rotation is represented by a predicate which maps one arrangement of tiles, to another. The first argument is the name of the rotation, while the second and third arguments represent a clockwise turn of the side. For example, the rotation of the upper side is represented by:

mov(u, cube(X1, …X6, X7, X8, X9, …),
cube(X1, …X6, X20, X19, X21, …))

We can apply this rotation to the top of the goal cube:

?- goalstate(State), mov(u, State, NewState).

The variable NewState would now have a solved cube with the upper side rotated clockwise.

Since these can be used in either direction, we can write a higher level predicate that will make either type of move based on a sign attached to the move.

move(+M, OldState, NewState):-
mov(M, OldState, NewState).

move(-M, OldState, NewState):-
mov(M, NewState, OldState).

Having now built the basic rotations, it is necessary to represent the complex sequences of moves necessary to unscramble the cube. In this case the list notation is the best way to go. For example, a sequence which rotates three corner pieces is represented by:

seq(tc3, [+r, -u, -l, +u, -r, -u, +l, +u]).

The sequence can be applied to a cube using a recursive list predicate, move_list/3:

move_list([], X, X).

move_list( [Move|T], X, Z):-
move(Move, X, Y),
move_list(T, Y, Z).

At this point we have a very efficient representation of the cube and a means of rotating it. We next need to apply some expertise to the search for a solution.

4. Advanced Rules

The most obvious rule for solving Rubik’s cube is to attack it one piece at a time. The placing of pieces in the solved cube is done in stages. In Black & Taylor’s book they recognize six different stages which build the cube up from the left side to the right. Some examples of stages are: put the left side edge pieces in place, and put the right side corner pieces in place. Each stage has from one to four pieces that need placement. One of the advantages of writing expert systems directly in a programming language such as Prolog, is that it is possible to structure the heuristics in an efficient, customized fashion. That is what is done in this program.

The particular knowledge necessary to solve each stage is stored in predicates, which are then used by another predicate, stage/1, to set up and solve each stage. Each stage has a plan of pieces it tries to solve for. These are stored in the predicate pln/2. It contains the stage number and a list of pieces. For example, stage 5 looks for the four edge pieces on the right side:

pln(5, [p('R', 'U'), p('F', 'R'), p('R', 'D'), p('B', 'R')]).

Each stage will also use a search routine which tries various combinations of rotations to position a particular target piece. Different rotations are useful for different stages, and these too are stored in predicates similar to pln/2. The predicate is cnd/2 which contains the candidate rotations for the stage.

For example, the first stage (left edge pieces) can be solved using just the simple rotations of the right, upper, and front faces. The last stage (right corner pieces) requires the use of powerful sequences which exchange and twist corner pieces without disturbing the rest of the cube. These have names such as corner-twister 3 and tri-corner 1. They are selected from Black and Taylor’s book. These two examples are represented:

cnd(1, [r, u, f]).

cnd(6, [u, tc1, tc3, ct1, ct3]).

The stage/1 predicate drives each of the stages. It basically initializes the stage, and then calls a general purpose routine to improve the cube’s state. The initialization of the stage includes setting up the data structures that hold the plan for the stage and the candidate moves. Stage also reorients the cube for the stage to take advantage of symmetries and/or make for better displays.

Ditulis dalam Discrete Math, Literature Review, SWI - Prolog | Leave a Comment »

Prolog Simple Expert System (Step Of Six Counters)

Posted by madmathc pada November 24, 2009


Final Project

Simple Expert System Using Prolog

@author Mo2ncha’09

Assalamualaikum Wbr.

Kali ini kami memberikan contoh sebuah permasalahan sederhana, yaitu ada sebuah papan dengan 3 titik hitam dan 3 titik putih saling berhadapan dan di tengah-tengahnya diberikan ruang/spasi, seperti gambar dibawah ini:

Dari gambar diatas diketahui bahwa tujuannya adalah membuat urutan langkah yang tepat untuk menukarkan hitam dan putih saling berlawanan, dengan aturan yang berlaku adalah sebagai berikut:

  1. Hitam dan putih harus bergerak bergantian dan saling berlawanan arah
  2. Setiap biji hitam maupun putih dapat bergerak secara horizontal maupun vertikal
  3. setiap biji hitam maupun putih dapat melompati satu biji lainnya kedalam sebuah ruang kosong

Bagaimana cara  menulis program Prolognya untuk mencari semua kemingkinan cara untuk melakukan hal tersebut tanpa perulangan?  Sebagai contoh, input query yang kita masukkan adalah:

?-play (w,s(w,w,w,e,b,b,b),s(b,b,b,e,w,w,w),S,R).

maka Prolog harus menjawab seperti ini :



Penjelasannya adalah [w,2,4] menunjukkan biji putih akan bergerak dari posisi 2 sampai dengan posisi 4, bukan dari output “,…,”. Tetapi setiap biji yang ada harus mengandung histori dari tiap-tiap tempat yang telah di tempati (setelah lompatan/jalan), jumlah maksimal gerakan yang ada mungkin berbeda konfigurasinya.

Cek query dari Prolognya:
?-play (_, s (w, w, w, e, b, b, b), s (b, b, e, w, w, b, w ),_,_).

  • Apa artinya jawaban ini? Petunjuk: pertama adalah memecahkan masalah untuk bermain / 4 tanpa R variabel.
  • Bagaimana cara mencari pergerakan alternatifnya (alternate movement?)

Solusinya (mudah-mudahan kalau saya tidak salah):
%pergerakan tepi pinggir/corner edge movement
move(C, 1, 2, s(C, e, X3, X4, X5, X6, X7), s(e, C, X3, X4, X5, X6, X7)).
move(C, 1, 3, s(C, X2, e, X4, X5, X6, X7), s(e, X2, C, X4, X5, X6, X7)).
move(C, 7, 5, s(X1, X2, X3, X4, e, X6, C), s(X1, X2, X3, X4, C, X6, e)).
move(C, 7, 6, s(X1, X2, X3, X4, X5, e, C), s(X1, X2, X3, X4, X5, C, e)).

% pergerakan arah tengah/center edge movement
move(C, 4, 2, s(X1, e, X3, C, X5, X6, X7), s(X1, C, X3, e, X5, X6, X7)).
move(C, 4, 3, s(X1, X2, e, C, X5, X6, X7), s(X1, X2, C, e, X5, X6, X7)).
move(C, 4, 5, s(X1, X2, X3, C, e, X6, X7), s(X1, X2, X3, e, C, X6, X7)).
move(C, 4, 6, s(X1, X2, X3, C, X5, e, X7), s(X1, X2, X3, e, X5, C, X7)).

% gerak melompat/jump movement
move(C, 2, 6, s(X1, C, X3, X4, X5, e, X7), s(X1, e, X3, X4, X5, C, X7)).
move(C, 3, 5, s(X1, X2, C, X4, e, X6, X7), s(X1, X2, e, X4, C, X6, X7)).

% menjelaskan semua kemungkinan gerakan — 20 gerakan dari segala arah
% define all the required movement — 20 movements from all directions
make_movement(C, N1, N2, List1, List2) :- move(C, N1, N2, List1, List2).
make_movement(C, N1, N2, List1, List2) :- move(C, N2, N1, List2, List1).

% Pergerakan alternatif dari biji hitam dan biji putih
% alternate moving a black counter and a white counter
nextPlayer(b, w).
nextPlayer(w, b).
alternate(Present, Next) :- nextPlayer(Present, Next).

play_move(C, X, X, A, [X], []).
play_move(C, X, Y, A, [X|P], [[C, N1, N2]|B]) :- make_movement(C, N1, N2, X, Z),
alternate(C, Next),
not(member(Z, [X|A])),
play_move(Next, Z, Y, [X|A], P, B).
play(C, X, Y, S, R):- play_move(C, X, Y, [], S, R).

Mohon saran dan kritiknya jika terdapat kesalahan dalam posting ini.

Wassalamualaikum Wbr.

Mo2ncha dkk

Ditulis dalam Discrete Math, SWI - Prolog, Tutorial | Leave a Comment »


Posted by madmathc pada November 24, 2009

Berikut adalah resume dari Input dan Output pada Prolog.

Tujuannya:  adalah agar user mampu Menggunakan predikat built-in  baik untuk terminal (keyboard dan layar) atau file, dan mampu menggunakan nilai ASCII untuk memanipulasi string karakter.

Fungsi masukan dan keluaran (I/O atau Input/Output) dalam Prolog yaitu WRITE dan READ. Fungsi WRITE digunakan untuk menulis nilai atau ekspresi, sedangkan fungsi READ digunakan untuk menerima masukan dari keyboard.
Contoh :
(save as program dibawah ini dengan nama
write(“tuliskan sebuah kata : “),readln(X),
write(“kata yang saya ketik tadi adalah “),
• ‘eksekusi’ merupakan deklarasi predikat.
• Karena goal menjalankan ‘eksekusi’, maka program akan menjalankan urutan eksekusi yang ada pada clauses.
• Saat Test goal, perintah write akan memunculkan “tuliskan sebuah kata : “ pada layar.
• Setelah user menginputkan suatu kata (dan tekan Enter), maka kata tersebut akan dimasukkan ke dalam variable ‘X’.
• Kemudian pada layar muncul “kata yang saya ketik tadi adalah “
lalu perintah write(X) akan menampilkan isi dari variable ‘X’ tersebut.
NB: syntax nl adalah untuk ganti baris.


Ditulis dalam Discrete Math, SWI - Prolog, Tutorial | Leave a Comment »

Operators and Arithmetics ch.2

Posted by madmathc pada November 13, 2009



4.1 Operator-Operator

Penggunaan notasi untuk predikat secara standar menggunakan sebuah fungsi yang diikuti oleh sebuah angka dari argumen dalam tanda kurung, misalnya cinta(momon,nida). Cara lain menetapkan predikat dengan dua argumen dari sebuah predikat kembar dapat di konversi menjadi sebuah infix operator (Operator sisipan). Cara demikian akan mempermudah functor atau nama dari predikat untuk dituliskan diantara dua argumen tanpa tanda kurung, misalnya: momon cinta nida. Dengan demikian cara tersebut lebih memudahkan functor dibaca sebelum argumen tanpa tanda kurung, misal heli_anjing momon ketimbang menggunakan heli_anjing(momon). Cara lain, sebuah predikat dengan satu argumen (unary predicate) dapat di konversikan menjadi sebuah postfix operator (Operator dibelakang operand). Ini memungkinkan functor untuk ditulis setelah argumen, misal momon heli_anjing .

Notasi operator dapat pula digunakan dengan rules untuk mempermudah pembacaan. Sebagai contoh rule adalah cinta(momon,X):-is_wanita(X),memiliki(X,Y),isa_kucing(Y). Lebih mudah dimengerti jika rules ditulis sebagai momon cinta X:- X is_wanita, X memiliki Y, Y isa_kucing. Notasi tanda kurung  functor dan argumen  misal: cinta(momon,X) maka masih dapat digunakan dengan operator-operator jika lebih memilih hal tersebut.Notasi ‘Mixed’ atau campuran juga diperbolehkan, misal: cinta/2, is_wanita/1, memiliki/2 and isa_kucing/1 adalah semua operator yang sama dengan (momon,X):-is_wanita(X),X memiliki Y,isa_kucing(Y). Ada pula yang menetapkan predikat dengan satu atau dua dapat di konversikan menjadi sebuah operator dengan memasukkan hasil dengan predikat op pada sistem prompt. Predikat tersebut memakai tiga argumen, sebagai contoh  ?-op(150,xfy,cinta).

Argumen pertama adalah ‘operator precedence’, atau operator yang lebih didahulukan yang merupakanbilangan integer positif. Jarak dari angka-angka digunakan tergantung  dari implementasi khusus. Angka yang lebih kecil akan didahulukan. Nilai dari Operator precedence digunakan untuk  menentukan operator manakah yang akan digunakan pada saat tertentu akan digunakan lebih dari satu kali.

Sebuah predikat juga dapat di konversikan kedalam sebuah operator dengan menempatkan baris seperti


Dalam aplikasi Prolog file akan dimasukkan menggunakan consult atau reconsult.  Sebagai catatan bahwa prompt (dua karakter ?-) harus dimasukkan. Ketika sebuah hasil digunakan  dengan cara tersebut, keseluruhan baris dikenal sebagai directive atau instruksi. Dalam kasus ini directive harus ditempatkan pada file sebelum klausa pertama yang menggunakan operator cinta. Termasuk didalamnya relational operators untuk membandingkan nilai numerik, termasuk  menunjukkan kurang dari dan menunjukkan lebih besar dari. Sebagai contoh term yang benar:




Notasi tanda kurung dapat pula digunakan dengan predikat pembangun ditetapkan sebagai operator contoh >(X,4) daripada X>4.

4.2. Arithmetic (Aritmatika)

Disamping penggunaan non-angka (hewan atau nama), Prolog juga menyediakan fasilitas untuk melakukan perhitungan aritmatika dengan menggunakan notasi yang mirip dengannya, yang tentu saja cukup akrap dengan aljabar dasar. Dapat digunakan dengan predikat built-in is/2 yang dikenal sebagai operator infix (sisipan) dan demikian ditulis diantara dua argumen. Mengevaluasi hasil X is -6.5 akan menyebabkan X terbatas pada angka -6.5 sehingga hasil tercapai. Argumen kedua dapat pula sebagai angka atau atau perhitungan aritmatika, contoh: X is 6*Y+Z-3.2+P-Q/4 (* menunjukkan perkalian). variabel-variabel yang muncul dalam operasi aritmatika harus telah dibatasi sebagai hasil dari evaluasi hasil sebelumnya dan nilai-nilainya haruslah berwujud angka.  Jika disajikan demikian, hasil akan selalu berhasil dan wujud variabel argumen pertama akan terbatas dari nilai operasi aritmatika. Jika tidak sebuah pesan error akan muncul. Contoh:

?- X is 10.5+4.7*2.

X = 19.9

?- Y is 10,Z is Y+1.

Y = 10 ,

Z = 11

Simbol-simbol seperti + – * / dalam operasi aritmatika adalah tipe spesial dari operator sisipan (  infix operator ) yang dikenal sebagai arithmetic operators atau operator-operator aritmatika. Tidak seperti operator lain yang digunakan pada Prolog, mereka bukanlah predikat melainkan fungsi-fungsi,yang menghasilkan nilai numerik. Sama halnya dengan angka, variabel dan operator, operasi aritmatik dapat mencakup fungsi aritmatik, tertulis dengan argumen-argumen dalam tanda kurung.Misal operasi aritmatika untuk menghitung akar kuadrat dari 36 :

?- X is sqrt(36).

X = 6

Operator Aritmatika dapat pula digunakan tidak sebagai operator sisipan biner untuk menunjukkan perbedaan antara dua nilai numerik, contoh X-6, tapi juga sebagai operator awalan unary digunakan untuk menunjukkan numerik bernilai negatif, contoh:

?- X is 10,Y is -X-2.

X = 10 ,

Y = -12

Tabel dibawah  (dalam bahasa Inggris) menunjukkan beberapa operator aritmatika dan fungsi aritmatika yang tersedia dalam Prolog:

tabel aritmatik

Sebagai contoh:

?- X is 30,Y is 5,Z is X+Y+X*Y+sin(X).

X = 30 ,

Y = 5 ,

Z = 185.5

Meskipun predikat is umumnya digunakan untuk menguraikan, argumen pertama dapat pula sebagai variabel angka atau batasan dengan nilai numerik. Pada kasus tersebut jika nilai numerik dari dua argumen di kalkulasikan. Hasil tercapai jika hasil sama dengan, jika tidak maka gagal, contoh:

?- X is 7,X is 6+1.

X = 7

?- 10 is 7+13-11+9.


?- 18 is 7+13-11+9.


Catatan bahwa hasil dari X is X+1 akan selalu gagal, apakah X dibatasi atau tidak, contoh:

?- X is 10,X is X+1.


Catatan bahwa hasil dari X is X+1 akan selalu gagal, apakah X dibatasi atau tidak, contoh:

?- X is 10,X is X+1.


Untuk menaikkan (increase) nilai sebanyak satu membutuhkan pendekatan yang berbeda, misal:

Versi yang salah : increase(N):-N is N+1. Maka hasilnya:

?- increase(4).


Versi yang benar : increase(N,M):-M is N+1., maka hasilnya:

?- increase(4,X).

X = 5

4.2.1.  Operator Precedence (Operator yang lebih dahulu/Presedensi) pada Operasi Aritmatika

Ketika terdapat lebih dari satu operator pada operasi misal :A+B*C-D, Prolog membutuhkan sebuah pengertian untuk memutuskan perintah yang mana yang akan digunakan. Untuk operator dasar seperti + – * / ,perhitungan A+B*C-D harus ditafsirkan sebagai “perhitungan hasil dari B dan C, ditambahkan ke A kemudian dikurangi D”, tidak seperti “menambahkan A dan B, kemudian mengalikan C dan dikurangi D”. Prolog mampu mencapai hal demikian dengan memberikan masing-masing operator sebuah nilai numerik yang didahulukan (numerical precedence value), operator dengan tingkat didahulukan lebih tinggi seperti * dan / , digunakan sebelum operator dengan tingkat pendahuluan lebih rendah (lower precedence) seperti +dan -. Operator dengan  tingkat presedensi/pendahuluan yang sama misal + dan -, * dan / digunakan dari kiri ke kanan.  Efek dari memberikan operasi seperti A+B*C-D bagi yang memahami aljabar akan memandang dengan: A+(B*C)-D. Jika perintah berbeda dari dibutuhkan evaluasi, maka dapat diproses dengan tanda kurung, misal:  X is (A+B)*(C-D). Ekspresi dengan tanda kurung akan didahulukan.

4.2.2. Relational Operators (Operator-operator Hubungan)

Operator sisipan  (infix operators) =:= =\= > >= < =< adalah sebuah tipe istimewa yang dikenal sebagai relational operators atau operasi hubungan. Digunakan untuk membandingkan nilai dari dua buah ekspresi aritmatika. Hasil tercapai jika nilai dari ekspresi pertama adalah sama dengan, tidak sama dengan, lebih besar daripada, lebih besar atau sama dengan, kurang dari, atau kurang dari sama dengan nilai dari ekspresi kedua, berturut-turut. Kedua argumen harus berupa angka, dibatasi variabel atau ekspresi aritmatik. Contoh:

?- 88+15-3=:=110-5*2.


?- 100=\=99.


4.3 Equality Operators (Operator Persamaan)

Terdapat tiga tipe dari operator persamaan untuk mengetes persamaan dan pertidakpersamaan yang tersedia pada Prolog. Tipe pertama digunakan untuk membandingkan nilai dari ekspresi aritmatika, sedangkan yang kedua digunakan untuk membandingkan syarat (terms).

4.3.1. Ekspresi Aritmatika persamaan =:=

E1=:=E2 akan sukses jika ekspresi aritmatika dari E1 dan E2 mengevaluasi nilai yang sama, contoh:

?- 6+4=:=6*3-8.


?- sqrt(36)+4=:=5*11-45.


untuk mengecek apakah sebuah integer (bilangan bulat) genap atau ganjil, kita dapat menggunakan predikat checkeven/1 seperti dibawah ini:

checkeven(N):-M is N//2,N=:=2*M. , maka hasilnya:

?- checkeven(12).


?- checkeven(23).


?- checkeven(-11).


?- checkeven(-30).


Operator pembagian bilangan bulat // membagi argumen pertama dengan yang kedua dan mengkerucutkan hasilnya kepada bilangan bulat yang terdekat diantara bilangan tersebut dan nol. Jadi 12//2 adalah 6, 23//2 adalah 11, -11//2 adalah -5 and -30//2 adalah -15. Pembagian sebuah bilangan bulat dengan 2 menggunakan //dan mengalikannya lagi dengan 2 akan menghasilkan bilangan bulat tersebut sebagai genap, tetapi tidak sebaliknya.

4.3.2. Arithmetic Expression Inequality (Pertidaksamaan Ekspresi Aritmatika) =\=

E1=\=E2 dinilai berhasil jika ekspresi aritmatik E1 dan E2 tidak mengevaluasi nilai yang sama, contoh:

?- 10=\=8+3.


4.3.3. Terms Identical (Hubungan identikal) ==

Kedua argumen dari operator sisipan (infix operators) == harus saling berhubungan, hasil dari Term1==Term2 akan tercapai jika dan hanya jika (iff) Term1 adalah identik dengan Term2. Apapun variabel yang digunakan pada terms mungkin atau belum terbatas, tetapi tidak ada variabel yang terbatas sebagai hasil dari  evaluasi hasil (goal evaluation), contoh:

?- likes(X,prolog)==likes(X,prolog).

X = _

?- likes(X,prolog)==likes(Y,prolog).


(dengan X dan Y adalah variabel yang berbeda)

?- X is 10,pred1(X)==pred1(10).

X = 10

?- X==0.


?- 6+4==3+7.


Nilai dari ekspresi aritmatik hanya dievaluasi jika digunakan dengan operator is/2. Terdapat 6+4 contoh sederhana hubungan dengan functor + dan argumen 6 dan 4. Sangat berbeda dengan hubungan 3+7.

4.3.4. Terms Not Identical (Hubungan tidak identik) \==

Term1\==Term2 akan mengetes apakah Term1 adalah tidak identik dengan Term2. Hasil akan tercapai jika Term1==Term2 tidak tercapai. Selain dari itu akan gagal.contoh:

?- pred1(X)\==pred1(Y).

X = _ ,

Y = _

(Keluaran menandakan bahwa antara X dan Y tidak dibatasi dan merupakan variabel yang berbeda.)

4.3.5. Terms Identical With Unification (Hubungan Identik Dengan Penggabungan) =

Operator hubungan persamaan = mirip dengan == dengan sebuah perbedaan yang vital dan terkadang sangat berguna. Hasil dari Term1=Term2 akan tercapai jika hubungan Term1 and Term2 menyatu, contoh:

?- pred1(X)=pred1(10).

X = 10

(Dimana variabel X terikat pada 10, yang membuat dua hubungan identikal)

?- suka(X,prolog)=suka(momon,Y).

X = john ,

Y = prolog

(Mengikat X ke atom momon and Y to the atom prolog sehingga membuat dua hubungan identikal.)

?- X=0,X=:=0.

X = 0

(X=0 menyebabkan X terikat pada 0. hasil X=:=0 tercapai, yang memberitahukan bahwa X sekarang bernilai nol.)

?- 6+4=3+7.


?- 6+X=6+3.

X = 3

(Mengikat X pada 3 membuat dua hubungan identikal. Keduanga 6+3, tapi bukan angka 9.)

?- suka(X,prolog)=suka(

X = Y = _

(Mengikat X dan Y membuat hubungan identikal.)

?- suka(X,prolog)=likes(Y,ada).


(Tidak ada penyatuan membuat atom prolog dan ada identikal.)

4.3.6. Non-Unification Between Two Terms (Non-Penggabungan Antara Dua Hubungan) \=

Hasil dari Term1\=Term2 tercapai jika  Term1=Term2 gagal, diluar itu maka akan gagal, contoh:

?- 6+4\=3+7.


?- suka(X,prolog)\=suka(momon,Y).


(Karena mengikat X pada momon dan Y pada prolog akan membuat hubungan identikal.)

?- likes(X,prolog)\=likes(X,ada).

X = _

4.4.  Logical Operators (Operator Logika)

Membahas tentang penjelasan dari dua operator yang mengambil argumen yang disebut termsatau hubungan, dimana terms dapat diangap sebagai hasil.

4.4.1. The not Operator (Operator “Not”)

Operator awalan (prefix operator) not/1 dapat ditempatkan sebelum hasil apapun utnuk memberikan negasi terhadapnya. Hasil negasi akan tercapai jika hasil awal gagal dan akan gagal jika hasil awal tercapai. Contoh dibawah menggunakan not/1. Dengan mengasumsikan menggunakan satu klausa
?- not anjing(helli).
?- helli(burik).
?- not anjing(burik).
?- X=0,X is 0.
X = 0
?- X=0,not X is 0.

4.4.2. The Disjunction Operator (Operator Pemisahan)

Operator pemisahan ;/2 (ditulis dengan karakter titik koma) digunakan untuk mewakili ‘or’. Sebuah operator sisipan (Infix Operator) yang menggunakan dua argumen, keduanya adalah hasil (goals). Goal1;Goal2 tercapai jika salah satu dari Goal1 atau Goal2 tercapai.Contoh:

?- 6<3;7 is 5+2.


?- 6*6=:=36;10=8+3.


Sekian resume Tutorial Prolog Bab 4 : Operator And Arithmetic, mudah-mudahan dari apa yang kami kerjakan ini bermanfaat sehingga mengantar pada tujuan, khususnya bagi kami dan pada umumnya untuk pembaca sekalian.Amin  @MoMoNcha’09

Ditulis dalam Discrete Math, SWI - Prolog, Tutorial | Leave a Comment »

Operator and Arithmetic ch.1

Posted by madmathc pada November 13, 2009

Hello bloggers….

Now I will show u how to solve Practical Exercise about Operator and Arithmetic in Prolog.  These are the question  :

(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).
dog(fred). large(fred).
cat(henry). large(henry).
cat(steve). large(steve).
large_dog(X):- dog(X),large(X).
small_animal(A):- dog(A),small(A).
small_animal(B):- cat(B),small(B).
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).

Now, this is the answer….
Step 1 : Make your new rule in Notepad like this one…
Save it and don’t forget to type .pl at the end of your file name.

2.  Next, consult your file in Prolog. After that, type
?- X chases Y.
Then press Enter. After 1st answer, type ; to show another answer. This is the result…

gambar 4

Compare the result from the question above…


Same things, right…. :)


step1 : You must make rule like this…


Save it and don’t forget to type .pl at the end of your file name.

2.  Next, consult your file in Prolog. After that, try to type this…

?- pred(9,19).

Then press Enter. This is the result…

nomor 2

Those are the solution for this problem. For more explanation about this chapter, read Arithmetic n Operators ch. 2. This writing will be posted soon. Thank u and don’t forget to give a comment. :-)

Ditulis dalam Tutorial | Leave a Comment »

Rule-Based/Expert Systems

Posted by madmathc pada Oktober 21, 2009

Definition of Expert systems are:

- Knowledge based systems
- Part of the Artificial Intelligence field
- Computer programs that contain some subject-specific knowledge of one or more human experts
- Made up of a set of rules that analyze user supplied information about a specific class of problems.
- Systems that utilize reasoning capabilities and draw conclusions.

Terms Associated with Expert Systems
+ Knowledge Engineering – building an expert system
+ Knowledge Engineers – the people who build the system
+ Knowledge Representation – the symbols used to represent the knowledge
+ Factual Knowledge – knowledge of a particular task domain that is widely shared
+ Heuristic Knowledge – more judgmental knowledge of performance in a task domain.

Uses of Expert Systems
- Very useful to companies with a high-level of experience and expertise that cannot easily be transferred to other members.
- Solves problems that would normally be tackled by a medical or other professional.
- Currently used in fields such as accounting, medicine, process control, financial service, production, and human resources

Prominent Expert Systems
> MYCIN – used to diagnose infectious blood diseases and recommend antibiotics.
> DENDRAL – embedded a chemist’s knowledge of mass spectrometry rules to use in analysis.
> CADUCEUS – used to analyze blood-borne infectious bacteria
> CLIPS and Prolog programming languages are both used in expert systems
- The Age of Empire game uses CLIPS to control its AI

Building an Expert System
+ Can be built from scratch – using lots of if-then-else statements.
+ There are many products being sold to make programming these systems easier.
A few that I’m aware of:
- Exsys – – provides an easy to use user interface to develop traditional applications or web-based solutions.
- Barisoft – – developed by a PSU professor and finely tuned by his students
- CLIPS – provides a complete environment for the construction of rules and/or object based expert systems
- Jess – the Rule Engine, built

Components of an Expert System
> Set of Rules – derived from the knowledge base and used by the interpreter to evaluate the inputted data
> Knowledge Engineer – decides how to represent the experts knowledge and how to build the inference engine appropriately for the domain
> Interpreter – interprets the inputted data and draws a conclusion based on the users responses.

Problem-solving Models
+ Forward-chaining – starts from a set of conditions and moves towards some conclusion
+ Backward-chaining – starts with a list of goals and the works backwards to see if there is any data that will allow it to conclude any of these goals.
+ Both problem-solving methods are built into inference engines or inference procedures
Knowledge Objects
- Classes – questions the user is asked
- Parameters – place holder for a character string which can be variable and used to decide if/when a question is asked
- Procedures – definitions of calls to external procedures
- Rule Nodes – inferencing is done by a tree structure (decision trees!) and the nodes are called rule nodes.

Advantages of Expert Systems
+ Provide consistent answers for repetitive decisions, processes and tasks.
+ Hold and maintain significant levels of information.
+ Reduce employee training costs
+ Centralize the decision making process.
+ Create efficiencies and reduce the time needed to solve problems.
+  Combine multiple human expert intelligences
+ Reduce the amount of human errors.
+ Give strategic and comparative advantages creating entry barriers to competitors
+ Review transactions that human experts may overlook.

Disadvantages of Expert Systems
> Lack human common sense needed in some decision making.
> Will not be able to give the creative responses that human experts can give in unusual circumstances.
> Domain experts cannot always clearly explain their logic and reasoning.
> Challenges of automating complex processes.
> Lack of flexibility and ability to adapt to changing environments.
> Not being able to recognize when no answer is available.

References :
- “Expert Systems and Artificial Intelligence”. Engelmore, R., Feigenbaum, E., Chapter 1.
- “The Origin of Rule-Based Systems in AI”, Davis, R., King, J.
- “Expert System – Wikipedia”,

Ditulis dalam Literature Review | Leave a Comment »

Facts, Rules, Predicates, and Variables in PROLOG

Posted by madmathc pada Oktober 21, 2009

(1) Type the following program into a file and load it into Prolog.

/* Animals Database */

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 */

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.

Okay, guys! This is our homework for this time. So, how can we find the answer? Now, this is the solution….
Question Number 1
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. The answer must be No, because there is no reptile has mane in that program.


Question Number 2

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.

Clip_104. Consult your saved file in PROLOG.
5. To find the answer, type this
?- couple(X,Y).
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.

This is the end of this section. Don’t forget to give comment for our blog. Thank u. (^_^)!!

Ditulis dalam Tutorial | Leave a Comment »


Get every new post delivered to your Inbox.