Prolog – Discussion

Discuss Prolog ”; Previous Next Prolog or PROgramming in LOGics is a logical and declarative programming language. It is one major example of the fourth generation language that supports the declarative programming paradigm. This is particularly suitable for programs that involve symbolic or non-numeric computation. Print Page Previous Next Advertisements ”;

Monkey and Banana Problem

Prolog – Monkey and Banana Problem ”; Previous Next In this prolog example, we will see one very interesting and famous problem, The Monkey and Banana Problem. Problem Statement Suppose the problem is as given below − A hungry monkey is in a room, and he is near the door. The monkey is on the floor. Bananas have been hung from the center of the ceiling of the room. There is a block (or chair) present in the room near the window. The monkey wants the banana, but cannot reach it. So how can the monkey get the bananas? So if the monkey is clever enough, he can come to the block, drag the block to the center, climb on it, and get the banana. Below are few observations in this case − Monkey can reach the block, if both of them are at the same level. From the above image, we can see that both the monkey and the block are on the floor. If the block position is not at the center, then monkey can drag it to the center. If monkey and the block both are on the floor, and block is at the center, then the monkey can climb up on the block. So the vertical position of the monkey will be changed. When the monkey is on the block, and block is at the center, then the monkey can get the bananas. Now, let us see how we can solve this using Prolog. We will create some predicates as follows − We have some predicates that will move from one state to another state, by performing action. When the block is at the middle, and monkey is on top of the block, and monkey does not have the banana (i.e. has not state), then using the grasp action, it will change from has not state to have state. From the floor, it can move to the top of the block (i.e. on top state), by performing the action climb. The push or drag operation moves the block from one place to another. Monkey can move from one place to another using walk or move clauses. Another predicate will be canget(). Here we pass a state, so this will perform move predicate from one state to another using different actions, then perform canget() on state 2. When we have reached to the state ‘has>’, this indicates ‘has banana’. We will stop the execution. Program move(state(middle,onbox,middle,hasnot), grasp, state(middle,onbox,middle,has)). move(state(P,onfloor,P,H), climb, state(P,onbox,P,H)). move(state(P1,onfloor,P1,H), drag(P1,P2), state(P2,onfloor,P2,H)). move(state(P1,onfloor,B,H), walk(P1,P2), state(P2,onfloor,B,H)). canget(state(_,_,_,has)). canget(State1) :- move(State1,_,State2), canget(State2). Output | ?- [monkey_banana]. compiling D:/TP Prolog/Sample_Codes/monkey_banana.pl for byte code… D:/TP Prolog/Sample_Codes/monkey_banana.pl compiled, 17 lines read – 2167 bytes written, 19 ms (31 ms) yes | ?- canget(state(atdoor, onfloor, atwindow, hasnot)). true ? yes | ?- trace . The debugger will first creep — showing everything (trace) yes {trace} | ?- canget(state(atdoor, onfloor, atwindow, hasnot)). 1 1 Call: canget(state(atdoor,onfloor,atwindow,hasnot)) ? 2 2 Call: move(state(atdoor,onfloor,atwindow,hasnot),_52,_92) ? 2 2 Exit:move(state(atdoor,onfloor,atwindow,hasnot),walk(atdoor,_80),state(_80,onfloor,atwindow,hasnot)) ? 3 2 Call: canget(state(_80,onfloor,atwindow,hasnot)) ? 4 3 Call: move(state(_80,onfloor,atwindow,hasnot),_110,_150) ? 4 3 Exit: move(state(atwindow,onfloor,atwindow,hasnot),climb,state(atwindow,onbox,atwindow,hasnot)) ? 5 3 Call: canget(state(atwindow,onbox,atwindow,hasnot)) ? 6 4 Call: move(state(atwindow,onbox,atwindow,hasnot),_165,_205) ? 6 4 Fail: move(state(atwindow,onbox,atwindow,hasnot),_165,_193) ? 5 3 Fail: canget(state(atwindow,onbox,atwindow,hasnot)) ? 4 3 Redo: move(state(atwindow,onfloor,atwindow,hasnot),climb,state(atwindow,onbox,atwindow,hasnot)) ? 4 3 Exit: move(state(atwindow,onfloor,atwindow,hasnot),drag(atwindow,_138),state(_138,onfloor,_138,hasnot)) ? 5 3 Call: canget(state(_138,onfloor,_138,hasnot)) ? 6 4 Call: move(state(_138,onfloor,_138,hasnot),_168,_208) ? 6 4 Exit: move(state(_138,onfloor,_138,hasnot),climb,state(_138,onbox,_138,hasnot)) ? 7 4 Call: canget(state(_138,onbox,_138,hasnot)) ? 8 5 Call: move(state(_138,onbox,_138,hasnot),_223,_263) ? 8 5 Exit: move(state(middle,onbox,middle,hasnot),grasp,state(middle,onbox,middle,has)) ? 9 5 Call: canget(state(middle,onbox,middle,has)) ? 9 5 Exit: canget(state(middle,onbox,middle,has)) ? 7 4 Exit: canget(state(middle,onbox,middle,hasnot)) ? 5 3 Exit: canget(state(middle,onfloor,middle,hasnot)) ? 3 2 Exit: canget(state(atwindow,onfloor,atwindow,hasnot)) ? 1 1 Exit: canget(state(atdoor,onfloor,atwindow,hasnot)) ? true ? (78 ms) yes Print Page Previous Next Advertisements ”;

Prolog – Inputs and Outputs

Prolog – Inputs and Outputs ”; Previous Next In this chapter, we will see some techniques to handle inputs and outputs through prolog. We will use some built in predicates to do these tasks, and also see file handling techniques. Following topics will be discussed in detail − Handling inputs and outputs File handling using Prolog Using some external file to read lines and terms Character manipulation for input and output Constructing and decomposing atoms Consulting prolog files into other prolog program techniques. Handling input and output So far we have seen that we can write a program and the query on the console to execute. In some cases, we print something on the console, that are written in our prolog code. So here we will see that writing and reading tasks in more detail using prolog. So this will be the input and output handling techniques. The write() Predicate To write the output we can use the write() predicate. This predicate takes the parameter as input, and writes the content into the console by default. write() can also write in files. Let us see some examples of write() function. Program | ?- write(56). 56 yes | ?- write(”hello”). hello yes | ?- write(”hello”),nl,write(”world”). hello world yes | ?- write(“ABCDE”) . [65,66,67,68,69] yes From the above example, we can see that the write() predicate can write the contents into the console. We can use ’nl’ to create a new line. And from this example, it is clear that, if we want to print some string on the console, we have to use single quotes (‘string‘). But if we use double quote (“string”), then it will return a list of ASCII values. The read() Predicate The read() predicate is used to read from console. User can write something in the console, that can be taken as input and process it. The read() is generally used to read from console, but this can also be used to read from files. Now let us see one example to see how read() works. Program cube :- write(”Write a number: ”), read(Number), process(Number). process(stop) :- !. process(Number) :- C is Number * Number * Number, write(”Cube of ”),write(Number),write(”: ”),write(C),nl, cube. Output | ?- [read_write]. compiling D:/TP Prolog/Sample_Codes/read_write.pl for byte code… D:/TP Prolog/Sample_Codes/read_write.pl compiled, 9 lines read – 1226 bytes written, 12 ms (15 ms) yes | ?- cube. Write a number: 2. Cube of 2: 8 Write a number: 10. Cube of 10: 1000 Write a number: 12. Cube of 12: 1728 Write a number: 8. Cube of 8: 512 Write a number: stop . (31 ms) yes | ?- The tab() Predicate The tab() is one additional predicate that can be used to put some blank-spaces while we write something. So it takes a number as an argument, and prints those many number of blank spaces. Program | ?- write(”hello”),tab(15),write(”world”). hello world yes | ?- write(”We”),tab(5),write(”will”),tab(5),write(”use”),tab(5),write(”tabs”). We will use tabs yes | ?- Reading/Writing Files In this section, we will see how we can use files to read from, and write into the files. There are some built-in predicates, that can be used to read from file and write into it. The tell and told If we want to write into a file, except the console, we can write the tell() predicate. This tell()predicate takes filename as argument. If that file is not present, then create a new file, and write into it. That file will be opened until we write the told command. We can open more than one file using tell(). When told is called, all files will be closed. Prolog Commands | ?- told(”myFile.txt”). uncaught exception: error(existence_error(procedure,told/1),top_level/0) | ?- told(“myFile.txt”). uncaught exception: error(existence_error(procedure,told/1),top_level/0) | ?- tell(”myFile.txt”). yes | ?- tell(”myFile.txt”). yes | ?- write(”Hello World”). yes | ?- write(” Writing into a file”),tab(5),write(”myFile.txt”),nl. yes | ?- write(“Write some ASCII values”). yes | ?- told. yes | ?- Output (myFile.txt) Hello World Writing into a file myFile.txt [87,114,105,116,101,32,115,111,109,101,32,65,83,67,73,73,32,118,97,108,117,101,115] Similarly, we can also read from files. Let us see some example of reading from file. The see and seen When we want to read from file, not from the keyboard, we have to change current input stream. So we can use see() predicate. This will take filename as input. When the read operation is completed, then we will use seen command. Sample File (sample_predicate.txt) likes(lili, cat). likes(jhon,dog). Output | ?- see(”sample_predicate.txt”), read(X), read(Y), seen, read(Z). the_end. X = end_of_file Y = end_of_file Z = the_end yes | ?- So from this example, we can see that using the see() predicate we can read from the file. Now after using seen command, the control transfers to the console again. So finally it takes input from console. Processing files of terms We have seen how to read specific contents (few lines) of a file. Now if we want to read/process all the contents of a file, we need to write a clause to process file (process_file), until we reach the end of the file. Program process_file :- read(Line), Line == end_of_file, % when Line is not not end of file, call process. process(Line). process_file :- !. % use cut to stop backtracking process(Line):- %this will print the line into the console write(Line),nl, process_file. Sample File (sample_predicate.txt) likes(lili, cat). likes(jhon,dog). domestic(dog). domestic(cat). Output | ?- [process_file]. compiling D:/TP Prolog/Sample_Codes/process_file.pl for byte code… D:/TP Prolog/Sample_Codes/process_file.pl compiled, 9 lines read – 774 bytes written, 23 ms yes | ?- see(”sample_predicate.txt”), process_file, seen. likes(lili,cat) likes(jhon,dog) domestic(dog) domestic(cat) true ? (15 ms) yes | ?- Manipulating characters Using read() and write() we can read or write the value of atoms, predicates, strings, etc. Now in this section we will see how to write single characters into the current output stream, or how to read from current input stream. So there are some predefined predicates to do these tasks. The put(C) and put_char(C) predicates We can use put(C) to write one character at a time into the current output stream. The output stream can be a file or the console. This C can be a character or an ASCII code in other version of Prolog like SWI prolog, but in GNU

Prolog – Hello World

Prolog – Hello World ”; Previous Next In the previous section, we have seen how to install GNU Prolog. Now, we will see how to write a simple Hello World program in our Prolog environment. Hello World Program After running the GNU prolog, we can write hello world program directly from the console. To do so, we have to write the command as follows − write(”Hello World”). Note − After each line, you have to use one period (.) symbol to show that the line has ended. The corresponding output will be as shown below − Now let us see how to run the Prolog script file (extension is *.pl) into the Prolog console. Before running *.pl file, we must store the file into the directory where the GNU prolog console is pointing, otherwise just change the directory by the following steps − Step 1 − From the prolog console, go to File > Change Dir, then click on that menu. Step 2 − Select the proper folder and press OK. Now we can see in the prolog console, it shows that we have successfully changed the directory. Step 3 − Now create one file (extension is *.pl) and write the code as follows − main :- write(”This is sample Prolog program”), write(” This program is written into hello_world.pl file”). Now let’s run the code. To run it, we have to write the file name as follows − [hello_world] The output is as follows − Print Page Previous Next Advertisements ”;

Prolog – Home

Prolog Tutorial PDF Version Quick Guide Resources Job Search Discussion Prolog or PROgramming in LOGics is a logical and declarative programming language. It is one major example of the fourth generation language that supports the declarative programming paradigm. This is particularly suitable for programs that involve symbolic or non-numeric computation. Audience This reference has been prepared for the beginners to help them understand the basics of prolog. Prerequisites For this tutorial, it is assumed that the reader has a prior knowledge in coding. Print Page Previous Next Advertisements ”;

Prolog – Quick Guide

Prolog – Quick Guide ”; Previous Next Prolog – Introduction Prolog as the name itself suggests, is the short form of LOGical PROgramming. It is a logical and declarative programming language. Before diving deep into the concepts of Prolog, let us first understand what exactly logical programming is. Logic Programming is one of the Computer Programming Paradigm, in which the program statements express the facts and rules about different problems within a system of formal logic. Here, the rules are written in the form of logical clauses, where head and body are present. For example, H is head and B1, B2, B3 are the elements of the body. Now if we state that “H is true, when B1, B2, B3 all are true”, this is a rule. On the other hand, facts are like the rules, but without any body. So, an example of fact is “H is true”. Some logic programming languages like Datalog or ASP (Answer Set Programming) are known as purely declarative languages. These languages allow statements about what the program should accomplish. There is no such step-by-step instruction on how to perform the task. However, other languages like Prolog, have declarative and also imperative properties. This may also include procedural statements like “To solve the problem H, perform B1, B2 and B3”. Some logic programming languages are given below − ALF (algebraic logic functional programming language). ASP (Answer Set Programming) CycL Datalog FuzzyCLIPS Janus Parlog Prolog Prolog++ ROOP Logic and Functional Programming We will discuss about the differences between Logic programming and the traditional functional programming languages. We can illustrate these two using the below diagram − From this illustration, we can see that in Functional Programming, we have to define the procedures, and the rule how the procedures work. These procedures work step by step to solve one specific problem based on the algorithm. On the other hand, for the Logic Programming, we will provide knowledge base. Using this knowledge base, the machine can find answers to the given questions, which is totally different from functional programming. In functional programming, we have to mention how one problem can be solved, but in logic programming we have to specify for which problem we actually want the solution. Then the logic programming automatically finds a suitable solution that will help us solve that specific problem. Now let us see some more differences below − Functional Programming Logic Programming Functional Programming follows the Von-Neumann Architecture, or uses the sequential steps. Logic Programming uses abstract model, or deals with objects and their relationships. The syntax is actually the sequence of statements like (a, s, I). The syntax is basically the logic formulae (Horn Clauses). The computation takes part by executing the statements sequentially. It computes by deducting the clauses. Logic and controls are mixed together. Logics and controls can be separated. What is Prolog? Prolog or PROgramming in LOGics is a logical and declarative programming language. It is one major example of the fourth generation language that supports the declarative programming paradigm. This is particularly suitable for programs that involve symbolic or non-numeric computation. This is the main reason to use Prolog as the programming language in Artificial Intelligence, where symbol manipulation and inference manipulation are the fundamental tasks. In Prolog, we need not mention the way how one problem can be solved, we just need to mention what the problem is, so that Prolog automatically solves it. However, in Prolog we are supposed to give clues as the solution method. Prolog language basically has three different elements − Facts − The fact is predicate that is true, for example, if we say, “Tom is the son of Jack”, then this is a fact. Rules − Rules are extinctions of facts that contain conditional clauses. To satisfy a rule these conditions should be met. For example, if we define a rule as − grandfather(X, Y) :- father(X, Z), parent(Z, Y) This implies that for X to be the grandfather of Y, Z should be a parent of Y and X should be father of Z. Questions − And to run a prolog program, we need some questions, and those questions can be answered by the given facts and rules. History of Prolog The heritage of prolog includes the research on theorem provers and some other automated deduction system that were developed in 1960s and 1970s. The Inference mechanism of the Prolog is based on Robinson’s Resolution Principle, that was proposed in 1965, and Answer extracting mechanism by Green (1968). These ideas came together forcefully with the advent of linear resolution procedures. The explicit goal-directed linear resolution procedures, gave impetus to the development of a general purpose logic programming system. The first Prolog was the Marseille Prolog based on the work by Colmerauer in the year 1970. The manual of this Marseille Prolog interpreter (Roussel, 1975) was the first detailed description of the Prolog language. Prolog is also considered as a fourth generation programming language supporting the declarative programming paradigm. The well-known Japanese Fifth-Generation Computer Project, that was announced in 1981, adopted Prolog as a development language, and thereby grabbed considerable attention on the language and its capabilities. Some Applications of Prolog Prolog is used in various domains. It plays a vital role in automation system. Following are some other important fields where Prolog is used − Intelligent Database Retrieval Natural Language Understanding Specification Language Machine Learning Robot Planning Automation System Problem Solving Prolog – Environment Setup In this chapter, we will discuss how to install Prolog in our system. Prolog Version

Prolog – Built-In Predicates

Prolog – Built-In Predicates ”; Previous Next In Prolog, we have seen the user defined predicates in most of the cases, but there are some built-in-predicates. There are three types of built-in predicates as given below − Identifying terms Decomposing structures Collecting all solutions So this is the list of some predicates that are falls under the identifying terms group − Predicate Description var(X) succeeds if X is currently an un-instantiated variable. novar(X) succeeds if X is not a variable, or already instantiated atom(X) is true if X currently stands for an atom number(X) is true if X currently stands for a number integer(X) is true if X currently stands for an integer float(X) is true if X currently stands for a real number. atomic(X) is true if X currently stands for a number or an atom. compound(X) is true if X currently stands for a structure. ground(X) succeeds if X does not contain any un-instantiated variables. The var(X) Predicate When X is not initialized, then, it will show true, otherwise false. So let us see an example. Example | ?- var(X). yes | ?- X = 5, var(X). no | ?- var([X]). no | ?- The novar(X) Predicate When X is not initialized, the, it will show false, otherwise true. So let us see an example. Example | ?- nonvar(X). no | ?- X = 5,nonvar(X). X = 5 yes | ?- nonvar([X]). yes | ?- The atom(X) Predicate This will return true, when a non-variable term with 0 argument and a not numeric term is passed as X, otherwise false. Example | ?- atom(paul). yes | ?- X = paul,atom(X). X = paul yes | ?- atom([]). yes | ?- atom([a,b]). no | ?- The number(X) Predicate This will return true, X stands for any number, otherwise false. Example | ?- number(X). no | ?- X=5,number(X). X = 5 yes | ?- number(5.46). yes | ?- The integer(X) Predicate This will return true, when X is a positive or negative integer value, otherwise false. Example | ?- integer(5). yes | ?- integer(5.46). no | ?- The float(X) Predicate This will return true, X is a floating point number, otherwise false. Example | ?- float(5). no | ?- float(5.46). yes | ?- The atomic(X) Predicate We have atom(X), that is too specific, it returns false for numeric data, the atomic(X) is like atom(X) but it accepts number. Example | ?- atom(5). no | ?- atomic(5). yes | ?- The compound(X) Predicate If atomic(X) fails, then the terms are either one non-instantiated variable (that can be tested with var(X)) or a compound term. Compound will be true when we pass some compound structure. Example | ?- compound([]). no | ?- compound([a]). yes | ?- compound(b(a)). yes | ?- The ground(X) Predicate This will return true, if X does not contain any un-instantiated variables. This also checks inside the compound terms, otherwise returns false. Example | ?- ground(X). no | ?- ground(a(b,X)). no | ?- ground(a). yes | ?- ground([a,b,c]). yes | ?- Decomposing Structures Now we will see, another group of built-in predicates, that is Decomposing structures. We have seen the identifying terms before. So when we are using compound structures we cannot use a variable to check or make a functor. It will return error. So functor name cannot be represented by a variable. Error X = tree, Y = X(maple). Syntax error Y=X>(maple) Now, let us see some inbuilt predicates that falls under the Decomposing structures group. The functor(T,F,N) Predicate This returns true if F is the principal functor of T, and N is the arity of F. Note − Arity means the number of attributes. Example | ?- functor(t(f(X),a,T),Func,N). Func = t N = 3 (15 ms) yes | ?- The arg(N,Term,A) Predicate This returns true if A is the Nth argument in Term. Otherwise returns false. Example | ?- arg(1,t(t(X),[]),A). A = t(X) yes | ?- arg(2,t(t(X),[]),A). A = [] yes | ?- Now, let us see another example. In this example, we are checking that the first argument of D will be 12, the second argument will be apr and the third argument will be 2020. Example | ?- functor(D,date,3), arg(1,D,12), arg(2,D,apr), arg(3,D,2020). D = date(12,apr,2020) yes | ?- The ../2 Predicate This is another predicate represented as double dot (..). This takes 2 arguments, so ‘/2’ is written. So Term = .. L, this is true if L is a list that contains the functor of Term, followed by its arguments. Example | ?- f(a,b) =.. L. L = [f,a,b] yes | ?- T =.. [is_blue,sam,today]. T = is_blue(sam,today) yes | ?- By representing the component of a structure as a list, they can be recursively processed without knowing the functor name. Let us see another example − Example | ?- f(2,3)=..[F,N|Y], N1 is N*3, L=..[F,N1|Y]. F = f L = f(6,3) N = 2 N1 = 6 Y = [3] yes | ?- Collecting All Solutions Now let us see the third category called the collecting all solutions, that falls under built-in predicates in Prolog. We have seen that to generate all of the given solutions of a given goal using the semicolon in the prompt. So here is an example of it. Example | ?- member(X, [1,2,3,4]). X = 1 ? ; X = 2 ? ; X = 3 ? ; X = 4 yes Sometimes, we need to generate all of the solutions to some goal within a program in some AI related applications. So there are three built-in predicates that will help us to get the results. These predicates are as follows − findall/3 setoff/3 bagof/3 These three predicates take three arguments, so we have written ‘/3’ after the name of the predicates. These are also known as meta-predicates. These

Tree Data Structure (Case Study)

Tree Data Structure (Case Study) ”; Previous Next So far we have seen different concepts of logic programming in Prolog. Now we will see one case study on Prolog. We will see how to implement a tree data structure using Prolog, and we will create our own operators. So let us start the planning. Suppose we have a tree as shown below − We have to implement this tree using prolog. We have some operations as follows − op(500, xfx, ‘is_parent’). op(500, xfx, ‘is_sibling_of’). op(500, xfx, ‘is_at_same_level’). And another predicate namely leaf_node(Node) In these operators, you have seen some parameters as (500, xfx, <operator_name>). The first argument (here 500) is the priority of that operator. The ‘xfx’ indicates that this is a binary operator and the <operator_name> is the name of the operator. These operators can be used to define the tree database. We can use these operators as follows − a is_parent b, or is_parent(a, b). So this indicates that node a is the parent of node b. X is_sibling_of Y or is_sibling_of(X,Y). This indicates that X is the sibling of node Y. So the rule is, if another node Z is parent of X and Z is also the parent of Y and X and Y are different, then X and Y are siblings. leaf_node(Node). A node (Node) is said to be a leaf node when a node has no children. X is_at_same_level Y, or is_at_same_level(X,Y). This will check whether X and Y are at the same level or not. So the condition is when X and Y are same, then it returns true, otherwise W is the parent of X, Z is the parent of Y and W and Z are at the same level. As shown above, other rules are defined in the code. So let us see the program to get better view. Program /* The tree database */ :- op(500,xfx,”is_parent”). a is_parent b. c is_parent g. f is_parent l. j is_parent q. a is_parent c. c is_parent h. f is_parent m. j is_parent r. a is_parent d. c is_parent i. h is_parent n. j is_parent s. b is_parent e. d is_parent j. i is_parent o. m is_parent t. b is_parent f. e is_parent k. i is_parent p. n is_parent u. n is_parent v. /* X and Y are siblings i.e. child from the same parent */ :- op(500,xfx,”is_sibling_of”). X is_sibling_of Y :- Z is_parent X, Z is_parent Y, X == Y. leaf_node(Node) :- + is_parent(Node,Child). % Node grounded /* X and Y are on the same level in the tree. */ :-op(500,xfx,”is_at_same_level”). X is_at_same_level X . X is_at_same_level Y :- W is_parent X, Z is_parent Y, W is_at_same_level Z. Output | ?- [case_tree]. compiling D:/TP Prolog/Sample_Codes/case_tree.pl for byte code… D:/TP Prolog/Sample_Codes/case_tree.pl:20: warning: singleton variables [Child] for leaf_node/1 D:/TP Prolog/Sample_Codes/case_tree.pl compiled, 28 lines read – 3244 bytes written, 7 ms yes | ?- i is_parent p. yes | ?- i is_parent s. no | ?- is_parent(i,p). yes | ?- e is_sibling_of f. true ? yes | ?- is_sibling_of(e,g). no | ?- leaf_node(v). yes | ?- leaf_node(a). no | ?- is_at_same_level(l,s). true ? yes | ?- l is_at_same_level v. no | ?- More on Tree Data Structure Here, we will see some more operations that will be performed on the above given tree data structure. Let us consider the same tree here − We will define other operations − path(Node) locate(Node) As we have created the last database, we will create a new program that will hold these operations, then consult the new file to use these operations on our pre-existing program. So let us see what is the purpose of these operators − path(Node) − This will display the path from the root node to the given node. To solve this, suppose X is parent of Node, then find path(X), then write X. When root node ‘a’ is reached, it will stop. locate(Node) − This will locate a node (Node) from the root of the tree. In this case, we will call the path(Node) and write the Node. Program Let us see the program in execution − path(a). /* Can start at a. */ path(Node) :- Mother is_parent Node, /* Choose parent, */ path(Mother), /* find path and then */ write(Mother), write(” –> ”). /* Locate node by finding a path from root down to the node */ locate(Node) :- path(Node), write(Node), nl. Output | ?- consult(”case_tree_more.pl”). compiling D:/TP Prolog/Sample_Codes/case_tree_more.pl for byte code… D:/TP Prolog/Sample_Codes/case_tree_more.pl compiled, 9 lines read – 866 bytes written, 6 ms yes | ?- path(n). a –> c –> h –> true ? yes | ?- path(s). a –> d –> j –> true ? yes | ?- path(w). no | ?- locate(n). a –> c –> h –> n true ? yes | ?- locate(s). a –> d –> j –> s true ? yes | ?- locate(w). no | ?- Advances in Tree Data Structures Now let us define some advanced operations on the same tree data structure. Here we will see how to find the height of a node, that is, the length of the longest path from that node, using the Prolog built-in predicate setof/3. This predicate takes (Template, Goal, Set). This binds Set to the list of all instances of Template satisfying the goal Goal. We have already defined the tree before, so we will consult the current code to execute these set of operations without redefining the tree database again. We will create some predicates as follows − ht(Node,H). This finds the height. It also checks whether a node is leaf or not, if so, then sets height H as 0, otherwise recursively finds the height of children of Node, and add 1 to them. max([X|R], M,A). This calculates the max element from the list, and a value M. So if M is maximum, then it returns M, otherwise, it returns the maximum element of list that is greater than M. To solve this, if given list is empty, return M as max element, otherwise check whether Head is greater than M or not, if so,

Prolog – Operators

Prolog – Operators ”; Previous Next In the following sections, we will see what are the different types of operators in Prolog. Types of the comparison operators and Arithmetic operators. We will also see how these are different from any other high level language operators, how they are syntactically different, and how they are different in their work. Also we will see some practical demonstration to understand the usage of different operators. Comparison Operators Comparison operators are used to compare two equations or states. Following are different comparison operators − Operator Meaning X > Y X is greater than Y X < Y X is less than Y X >= Y X is greater than or equal to Y X =< Y X is less than or equal to Y X =:= Y the X and Y values are equal X == Y the X and Y values are not equal You can see that the ‘=<’ operator, ‘=:=’ operator and ‘==’ operators are syntactically different from other languages. Let us see some practical demonstration to this. Example | ?- 1+2=:=2+1. yes | ?- 1+2=2+1. no | ?- 1+A=B+2. A = 2 B = 1 yes | ?- 5<10. yes | ?- 5>10. no | ?- 10==100. yes Here we can see 1+2=:=2+1 is returning true, but 1+2=2+1 is returning false. This is because, in the first case it is checking whether the value of 1 + 2 is same as 2 + 1 or not, and the other one is checking whether two patterns ‘1+2’ and ‘2+1’ are same or not. As they are not same, it returns no (false). In the case of 1+A=B+2, A and B are two variables, and they are automatically assigned to some values that will match the pattern. Arithmetic Operators in Prolog Arithmetic operators are used to perform arithmetic operations. There are few different types of arithmetic operators as follows − Operator Meaning + Addition – Subtraction * Multiplication / Division ** Power // Integer Division mod Modulus Let us see one practical code to understand the usage of these operators. Program calc :- X is 100 + 200,write(”100 + 200 is ”),write(X),nl, Y is 400 – 150,write(”400 – 150 is ”),write(Y),nl, Z is 10 * 300,write(”10 * 300 is ”),write(Z),nl, A is 100 / 30,write(”100 / 30 is ”),write(A),nl, B is 100 // 30,write(”100 // 30 is ”),write(B),nl, C is 100 ** 2,write(”100 ** 2 is ”),write(C),nl, D is 100 mod 30,write(”100 mod 30 is ”),write(D),nl. Note − The nl is used to create new line. Output | ?- change_directory(”D:/TP Prolog/Sample_Codes”). yes | ?- [op_arith]. compiling D:/TP Prolog/Sample_Codes/op_arith.pl for byte code… D:/TP Prolog/Sample_Codes/op_arith.pl compiled, 6 lines read – 2390 bytes written, 11 ms yes | ?- calc. 100 + 200 is 300 400 – 150 is 250 10 * 300 is 3000 100 / 30 is 3.3333333333333335 100 // 30 is 3 100 ** 2 is 10000.0 100 mod 30 is 10 yes | ?- Print Page Previous Next Advertisements ”;

Prolog – Lists

Prolog – Lists ”; Previous Next In this chapter, we will discuss one of the important concepts in Prolog, The Lists. It is a data structure that can be used in different cases for non-numeric programming. Lists are used to store the atoms as a collection. In the subsequent sections, we will discuss the following topics − Representation of lists in Prolog Basic operations on prolog such as Insert, delete, update, append. Repositioning operators such as permutation, combination, etc. Set operations like set union, set intersection, etc. Representation of Lists The list is a simple data structure that is widely used in non-numeric programming. List consists of any number of items, for example, red, green, blue, white, dark. It will be represented as, [red, green, blue, white, dark]. The list of elements will be enclosed with square brackets. A list can be either empty or non-empty. In the first case, the list is simply written as a Prolog atom, []. In the second case, the list consists of two things as given below − The first item, called the head of the list; The remaining part of the list, called the tail. Suppose we have a list like: [red, green, blue, white, dark]. Here the head is red and tail is [green, blue, white, dark]. So the tail is another list. Now, let us consider we have a list, L = [a, b, c]. If we write Tail = [b, c] then we can also write the list L as L = [ a | Tail]. Here the vertical bar (|) separates the head and tail parts. So the following list representations are also valid − [a, b, c] = [x | [b, c] ] [a, b, c] = [a, b | [c] ] [a, b, c] = [a, b, c | [ ] ] For these properties we can define the list as − A data structure that is either empty or consists of two parts − a head and a tail. The tail itself has to be a list. Basic Operations on Lists Following table contains various operations on prolog lists − Operations Definition Membership Checking During this operation, we can verify whether a given element is member of specified list or not? Length Calculation With this operation, we can find the length of a list. Concatenation Concatenation is an operation which is used to join/add two lists. Delete Items This operation removes the specified element from a list. Append Items Append operation adds one list into another (as an item). Insert Items This operation inserts a given item into a list. Membership Operation During this operation, we can check whether a member X is present in list L or not? So how to check this? Well, we have to define one predicate to do so. Suppose the predicate name is list_member(X,L). The goal of this predicate is to check whether X is present in L or not. To design this predicate, we can follow these observations. X is a member of L if either − X is head of L, or X is a member of the tail of L Program list_member(X,[X|_]). list_member(X,[_|TAIL]) :- list_member(X,TAIL). Output | ?- [list_basics]. compiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code… D:/TP Prolog/Sample_Codes/list_basics.pl compiled, 1 lines read – 467 bytes written, 13 ms yes | ?- list_member(b,[a,b,c]). true ? yes | ?- list_member(b,[a,[b,c]]). no | ?- list_member([b,c],[a,[b,c]]). true ? yes | ?- list_member(d,[a,b,c]). no | ?- list_member(d,[a,b,c]). Length Calculation This is used to find the length of list L. We will define one predicate to do this task. Suppose the predicate name is list_length(L,N). This takes L and N as input argument. This will count the elements in a list L and instantiate N to their number. As was the case with our previous relations involving lists, it is useful to consider two cases − If list is empty, then length is 0. If the list is not empty, then L = [Head|Tail], then its length is 1 + length of Tail. Program list_length([],0). list_length([_|TAIL],N) :- list_length(TAIL,N1), N is N1 + 1. Output | ?- [list_basics]. compiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code… D:/TP Prolog/Sample_Codes/list_basics.pl compiled, 4 lines read – 985 bytes written, 23 ms yes | ?- list_length([a,b,c,d,e,f,g,h,i,j],Len). Len = 10 yes | ?- list_length([],Len). Len = 0 yes | ?- list_length([[a,b],[c,d],[e,f]],Len). Len = 3 yes | ?- Concatenation Concatenation of two lists means adding the list items of the second list after the first one. So if two lists are [a,b,c] and [1,2], then the final list will be [a,b,c,1,2]. So to do this task we will create one predicate called list_concat(), that will take first list L1, second list L2, and the L3 as resultant list. There are two observations here. If the first list is empty, and second list is L, then the resultant list will be L. If the first list is not empty, then write this as [Head|Tail], concatenate Tail with L2 recursively, and store into new list in the form, [Head|New List]. Program list_concat([],L,L). list_concat([X1|L1],L2,[X1|L3]) :- list_concat(L1,L2,L3). Output | ?- [list_basics]. compiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code… D:/TP Prolog/Sample_Codes/list_basics.pl compiled, 7 lines read – 1367 bytes written, 19 ms yes | ?- list_concat([1,2],[a,b,c],NewList). NewList = [1,2,a,b,c] yes | ?- list_concat([],[a,b,c],NewList). NewList = [a,b,c] yes | ?- list_concat([[1,2,3],[p,q,r]],[a,b,c],NewList). NewList = [[1,2,3],[p,q,r],a,b,c] yes | ?- Delete from List Suppose we have a list L and an element X, we have to delete X from L. So there are three cases − If X is the only element, then after deleting it, it will return empty list. If X is head of L, the resultant list will be the Tail part. If X is present