This action might not be possible to undo. Are you sure you want to continue?
< Prolog This page may need to be reviewed for quality. Jump to: navigation, search This section covers the installation of a prolog compiler, loading your first program, and querying it. It then explains how to use facts and variables in your programs and queries.
• • • • • •
1 Getting Started 2 First Steps 3 Syntax, Facts and Queries 4 Variables 5 Examples 6 Exercises
 Getting Started
Before anything can be done, a prolog compiler and a text editor need to be installed on your system. A text editor will allow you to write your prolog programs and the prolog compiler (also known as the interpreter) will allow you to execute them. Prolog Compilers The following prolog implementations are free (at least for personal or educational use, be sure to read the terms). Simply download one and install it according to the instructions on the website:
SWI Prolog (recommended for use with this book)
http://www.swi-prolog.org/ A small and robust open-source implementation that is compliant with both Prolog standards (ISO and Edinburgh) and has many extra libraries and built-in predicates. There's even a separate toolkit for creating windows and graphics, called XPCE. Supports many platforms.
http://www.gprolog.org/ (was: http://pauillac.inria.fr/~diaz/gnu-prolog/ ) A relatively new open source implementation. Has support for Constraint Logic Programming, an extension of prolog.
http://www.visual-prolog.com/ A complete development environment for an Object-Oriented extension of Prolog. Includes compiler, linker, text editor, graphical dialog editors, build system, debugger, large library, and much more The following implementations aren't free:
http://www.sics.se/ Probably the most well known professional prolog implementation and development suite. ISO-compliant, many libraries and support for constraint logic programming. Free for evaluation.
http://www.sics.se/quintus/ An especially robust and dependable implementation intended for commercial use and research projects by the same company that makes SICSTUS. Free for evaluation. Text Editors The programs that you will write are simple text files, to be read and written with any text editor. Some prolog implementations come with their own editor, but for those that don't here's a list of text editors. These provide the basic function that are useful for writing prolog programs, such as indentation, bracket matching and some can even be adjusted to highlight the syntax of your prolog code.
http://www.crimsoneditor.com/ A free text-editor for windows with many features.
http://www.gnu.org/software/emacs/emacs.html A free, open-source implementation of unix' classic text editor. May be difficult to understand, has lots of features.
http://www.vim.org/ A free, open-source implementation of Emacs' long-standing rival.
http://www.textpad.com/ A windows text-editor with many features. Free for evaluation.
Eclipse Prolog Plugin
http://eclipse.ime.usp.br/projetos/grad/plugin-prolog/index.html A free plugin for Eclipse.
 First Steps
Once you've installed your prolog implementation, it's time to write the first program and load it into the interpreter (mainly to see if everything works). Fire up your text editor and create a text file with just the following line in it:
Be precise, capitalization is important in prolog, as is the period. This will be your program (also known as the database or the knowledge base). Give it a nice name like prolog1.pl and save it. Note: The extension pl isn't officially associated with prolog and can cause conflicts if you're also programming in Perl, which uses .pl as well. If this is a problem you can use pro or pr or anything you like just as well. Now start your prolog interpreter. Most prolog interpreters will show you a window with some startup information and then the line
with a cursor behind it. There is usually a menu for loading files into the interpreter. If there isn't, you can type the following to load your file:
And press enter. Once again, be precise, no capitals and remember the dot. Replace FILEPATH with the name and directory of your file. For instance if your file is located in C:\My Documents\Prolog\prolog1.pl then use
or the shorthand
Note that the slashes are the other way around, since the backslash (\) has special meaning in Prolog (and most other languages). If you are using a UNIX based system such as Linux, the commands may look something like this
Your interpreter will now hopefully tell you that the file is loaded correctly. If it doesn't, consult the help file or manual of your implementations on how to consult files. After some information you will see
To see if everything is working, type
(don't forget the period) and press Enter. Prolog will answer with a heartfelt
and prolog will answer
Who = john
Press enter and prolog will end with Yes and give you back your command line. To exit prolog, type
 Syntax, Facts and Queries
john) abc(def. but it's important to see it the right way. These are words. prolog will answer Yes. man(david).jkl.f . parent(john. your interpreter will not understand the program. because we have not added that fact to the database. prolog will answer No. in the previous example was a prolog sentence in the form of a predicate. woman(suzie). all lowercase. They're just chosen to show what meaning you have for the program. This also seems fairly obvious. eliza). This is important: if prolog can't prove something from the program. it means you are asking prolog if this statement is true. it will consider it not true.. eliza). It checks all the lines in the program to see if anyone matches the statement and answers Yes if it finds one. Prolog will answer no. parent(suzie. john). If it doesn't. so it consults your file. possibly followed by a number of terms. if you forget it. Clearly prolog can't see from the statement whether it's true. human(suzie). woman(eliza). Predicates consist of one word of one or more characters. parent(david. but for now we will stick to constants. Note that if you ask ?. We could easily replace the word human with the word spaceship everywhere and the interpreter wouldn't know the difference. and if you type woman(john). You should also be aware that the names chosen for the predicates and terms do not actually mean anything to the prolog interpreter.  Variables .ghi. This type of sentence is called a fact. The first character of both a predicate and a constant needs to be a letter. human(eliza).human(david). If you type human(john).' behind each line to show that the line is over. If we load the above program into the interpreter we can run a query on it. man(john). This is known as the closed world assumption.The line human(john). Using predicates we can add facts to a program: human(john). it answers No. The following are examples of valid predicates: human(john) father(david. If you ask prolog human(john). again all lowercase. Note the period '.d) The terms (the 'words' within parentheses) can take many forms. This is very important.m) tree p(a .
parent(john. man(david).human(A). eliza).parent(Parent. What we have now is still not a very expressive language. If we want to make it even more difficult for prolog we can use two predicates in our query. just like terms and predicates. for instance: . If you query prolog with more than one variable it will show you all instantiations of the variables for which the query is true: ?. If you press semicolon ('. prolog answers No. the term of the predicate is a variable. john). man(john). prolog will answer Yes and give you back your cursor.') prolog will show you the rest of the possibilities A = suzie . woman(suzie). so that all people in the database are human. because the predicates don't match. human(suzie). Consider the following query human(A). It can unify human(A) with human(john) by making A john. with the exception that it starts with an uppercase letter and can have both upper and lowercase characters after that. human(eliza). parent(david. ?. eliza). because the database contains the line human(john). A variable is a word. We can gain a lot more expressiveness by using variables in our query. parent(suzie. No. If you press enter. In other words. A = john Prolog will answer Which is true. Now. and attempt to unify each predicate with the query. and either a man or a woman human(david). Child). Parent = john Child = eliza . After eliza. No When prolog is asked a query with a variable it will check all lines of the program. indicating that there are no further possibilities.We'll update the program with human(david). you are asking prolog what A needs to be for human(A) to be true. human(john). Parent = david Child = john . A = eliza . Prolog will try to bind a term to the variable. This means that it will check if the query matches the predicate when the variables are instantiated a certain way. Parent = suzie Child = eliza . but it can't unify man(A) with human(john). woman(eliza).
indicating that both predicates need to be true. for the query to be true. so it will look for a new instantiation of human(A).f). whether it already exists or not. instead of just one. Prolog may make a choice for A. david). the query fails.human(abc) Would be true with the above fact in the database. prolog needs to find an instantiation for all three anonymous variables in the database. In your database will mean that any term. Prolog will answer A = david. It tries the next option: A = john. However if you ask prolog ?. So the query ?. A = suzie. There is one special variable. or a semi-colon to see more options. In the example above. If it has found two instantiations for A and B that make both predicates true. Since the predicate abc isn't in the database at all._. suzie). such as abc(d. ie you don't care which term it's bound to. The comma means and. It will not tell you how it instantiates _. You can press Enter to end the program. as long as it's bound to something. When you use this character in a query. If that fails it will try to find a new instantiation for the first predicate and so forth until it runs out of options. It finds B = david in the line parent(david.A). This will not be true by default. to satisy the first predicate that doesn't work with the second.human(A). Putting human(_).?.e. If you ask prolog ?. Now we are asking prolog for a human A who has a parent B. called the anonymous variable.abc(_.  Examples . It can't find any. A = john. The next section deals with this. Say it chooses A = suzie to satisfy human(A). for which the underscore (_) character is used. john). it needs to find an instantiation for parent(B. If we want to state that a specific group of objects has a certain property. prolog will first find an instantiation to make the first predicate true--say it make A equal to john--and then it will try to make the second predicate true--with A equal to john. You can use the anonymous variable in your database as well. parent(B. To check this query._). This is called backtracking. Now it needs to instantiate parent(B. john) and reports back to you A = john B = david If you press semicolon it will try to find a new instantiation for the second predicate. is human. _). no choice for B will satisfy parent(B. Here the anonymous variable is used to state a property of all objects. so prolog will give up its choice of suzie for A. To make the second predicate true.parent(A. and try another name. it will return them to you. we need rules. you basically say that you don't care how this variable is instantiated. prolog will first find human(david) in the program and unify A with david.
mary). So parent/2 describes a predicate like parent(john. subway). Don't worry if some people are returned more than once.  Exercises (x) Find a Family Tree somewhere. Contents [hide] • • 1 Rules 2 Rules with Variables . 3. tram). which women have both a father and a son in the database? Can you think of a way to display those women that do not have a father listed in the database? Can you describe what you would need to write such a query? The answers to select excercises can be found here: Prolog/Introduction/Answers Prolog/Rules < Prolog This page may need to be reviewed for quality. List the women in the database List the children in the database List all combinations of a father and his son. A = amsterdam . Jump to: navigation. The number behind the predicate describes how many arguments the predicate takes. subway). transport(amsterdam. tram). search This section deals with Rules. You can peruse w:Category:Family_trees for a suitable family tree. 4.transport(A. 1. a general way to state when a predicate is true. transport(A. parent/2.The following program describes the public transport systems of some cities: transport(dresden. man/1. transport(new_york. transport(amsterdam. tram). 2. Write prolog queries for the following commands and questions. Implement part of the tree (around ten people) in a prolog program using the predicates woman/1. We can ask prolog if there is a city which has both a tram system and a subway: ?. subway). or make one up (a real one will make it easier to check your answers). fail. We'll discover how to deal with this later on.
states that a corvette is a car if it has wheels and windows.car(corvette). With rules we state that a predicate is true.b. . directly. c.e. just defining objects and their properties. The first step to programming in prolog is the use of rules. b. If it can prove both these goals (which it can). haswindows(corvette). and get the sub-goals haswheels(corvette) and haswindows(corvette). it's not the same variable. it has nothing to do with the A in the second line. if b. haswheels(A) and haswindows(A) need to be true. c and d. it will bind A to corvette. d. haswindows(A). dog(A) :. This says that a is true.b. c. For example: bird(A) :. c. c and d are true. haswheels(corvette).  Rules with Variables We can use predicates with terms as well. e. prolog would take the query (or goal) a and from that generate the sub-goals b. as we could also simply state that a corvette is a car with car(corvette). A rule looks like this: a :. haswindows(corvette).hasfeathers(A). but d is only true if e is true.a. If we have the following database a :. Since e is also a fact. This way we can state. d. This isn't a very useful statement. and we were to ask prolog if a is true ?.haswheels(corvette). car(corvette) :. d :. If two sentences use the variable A. e. which leads to another sub-goal. If prolog is asked whether a corvette is a car with ?.barks(A). When using variables in a program it's important to note that a variable doesn't mean anything beyond the sentence it's in.• • 3 Examples 4 Exercises  Rules So far we haven't really been doing any programming. then car(corvette) must be true. It can see that b and c are true. The A in the first line simply shows that the term of the predicate bird needs to be the same as the term of the predicate hasfeathers.haswheels(A). The first line states that for car(A) to be true. as they are stated as facts. provided that other predicates are true. prolog will answer yes. We can however use variables in rules. for instance that anything is a car provided that it has wheels and windows: car(A) :.
father(X. No  Exercises If you've used any other programming language. it will be a predicate referring to itself. john). Father = david Child = john .Now we can return to our original program and add some rules. Father = john Child = eliza .parent(X. parent(david.father(Father. Mother = suzie Child = eliza . No  Examples ?. eliza).parent(X. eliza). woman(eliza). eliza). Prolog is particularly well suited for recursion.Y) :.Y) :. rather than a function. X = john . although in our case.father(X.mother(Mother. human(david). man(X). mother(X. We can ask prolog who is the father of eliza: ?.Y). man(david). human(eliza). human(suzie). Child). parent(suzie.Y). Prolog/Recursive Rules . human(john). man(john). No Or to list all fathers in the database and their respective children: ?. Go to the next section to see how and why this is done.Child). parent(john. which refers to a function calling itself. you may be familiar with recursion. woman(X). woman(suzie).
we would look at the defintions. Furthermore. Z). grandparent. This may work for a bloodline with four generations. Y). What we need is a definition for ancestor that works for any line of parents. steve). parent(A. B) :. we'd need a new line for ancestor as well. parent(nathan. parent(A. Is Steve the parent of an ancestor of John? Steve is a parent of Jim. It's not elegant. For instance. This is one of the most important mechanisms in Prolog. Y). we can say that person A is person C's ancestor if person A is a parent of an ancestor of C. no matter how long. Steve is certainly no parent of John. a parent. it still doesn't define ancestor properly.B). it becomes complete definition. X). parent(A.B) ancestor(A. grandparent(A.B) ancestor(A. B). parent(david. david). B). but if we were to add a fifth parent to the program. but it can be difficult to work with at first. In the first place. a lot of work and most importantly. Jump to: navigation. parent(Y. To achieve this we need to think about the definition of an ancestor. If we would write rules for all these situations we could define ancestor(A. parent(steve. That is. person P is person C's ancestor. X). so the . letting a rule refer to itself. john). jim). but used together with the first statement.B) ::::parent(A. X). so that doesn't apply. B). X). parent(Z.parent(A. if we were to ask ourselves if Steve is an ancestor of John. and defines with a rule when someone is someone's grandparent (if he's a parent of that person's parent).B) ancestor(A. great grandparent and so on. This doesn't sound very useful. parent(Y. What if we wanted to define when someone is an ancestor of someone else? That is. It shows a male line in a family tree. since we use the word ancestor in its own definition. parent(X. if P is C's parent. Clearly this is not the way to go. parent(X. parent(X. parent(jim. B). parent(X.< Prolog This page may need to be reviewed for quality. search This section is about using rules recursively.B) for this particular bloodline: ancestor(A. Contents [hide] • • • • 1 Recursive rules 2 Using recursive rules 3 Examples 4 Exercises  Recursive rules Consider the following program.
jim . meaning prolog has run out of memory. The second rule is recursive. It can unify parent(steve. X= X= X= X= No steve . In the example above. it uses ancestor to define ancestor.ancestor(steve. B).parent(A. is Jim an ancestor of John? Jim is a parent of David.ancestor(nathan. the definition looks like this: ancestor(A. john). but won't be able to unify parent(steve. jim . it wouldn't actually make a difference. Or all people that Nathan is an ancestor of: ?. It will then try the second line and come up with the sub-goals parent(steve. X). It will continue this until it's left with the subgoal ancestor(david. so prolog is left with the sub-goal ancestor(jim. B). is true. john).question becomes. prolog will first try line one of the definition. The first rule is called the stop predicate as it stops the predicate calling itself. X) and ancestor(X. The following guidelines should always be kept in mind when writing recursive rules. ancestor(X.john). B). ancestor(A. david . B) :. nathan . • Start with your stop predicate. using the first line of the definition. it can lead to all kinds of loops. steve . so is David an ancestor of John? Here we can use the first definition. which will usually cause stack overflows. In prolog. john) is true. X) with parent(steve.  Using recursive rules Using recursive rules is not without its dangers. X). john) with any line in the database. • Avoid recursion on the left .parent(A. B) :. When faced with the query ?. If you start with the recursive predicate prolog will try to search 'deeper' before seeing if it can stop recursing. Prolog is very comfortable with using recursive rules. because David is a parent of John. because parent(david. X= X= X= X= No david . john . It can very easily find all ancestors of John: ?.ancestor(X. but your program won't always be so clean and straight-forward. john) which. jim). Always put the non-recursive predicate before the recursive predicate.
Sometimes it's necessary to put the recursive element on the left. that is followed by a list. Functions and Equality. In most programming languages. You can see how this is implemented in the section Math.b." Then. or do a lot of unnecessary work. This is the same principle as the previous guideline. "The factorial of X is Y. use: a :. One thing that can easily be defined recursively is a list. and they're used in a recursive way. a.X). Contents [hide] • • • 1 Recursive rules 2 Using recursive rules 3 Examples . we would use the query ?. instead of a :. Jump to: navigation. these two definitions exactly define anything that is a list. search This section is about using rules recursively.  Examples • A classic example of a recursive function is the factorial function. for instance. we'll state that a list is a single element. That is. Together. This is one of the most important mechanisms in Prolog. since we usually use predicates instead of functions. In Prolog. we will instead define a predicate fact(X. you might learn recursion by writing a function fact(). put the recursive rule on the right.a. Lists are actually a very common structure in prolog programs.When writing a recursive rule. • Prolog/Recursive Rules < Prolog This page may need to be reviewed for quality. For instance. but don't do it unless you know why you're doing it. letting a rule refer to itself. The following chapter explains how. b. and returned a positive integer. prolog could either get stuck in infinite recursions.Y) which is equivalent to the statement. if at all possible. To define this recursively. to find the factorial of 7. Prolog will then tell us: X=5040. let prolog evaluate non recursive goals first. To end the recursion we need a second statement. If you recurse before you've evaluated the other sub-goals. In this context we'll consider a list a collection of things (elements) that are placed in some order. which took a positive integer as input.fact(7. but it can be difficult to work with at first. which says that a list is something that consists of an element.
the definition looks like this: ancestor(A. it still doesn't define ancestor properly. X). X). steve).B) ancestor(A. When faced with the query ?. we can say that person A is person C's ancestor if person A is a parent of an ancestor of C. It can unify parent(steve. What we need is a definition for ancestor that works for any line of parents. B). Is Steve the parent of an ancestor of John? Steve is a parent of Jim. X) with parent(steve. parent(david. jim). parent(X.ancestor(steve. if we were to ask ourselves if Steve is an ancestor of John. Y). Steve is certainly no parent of John. B). because David is a parent of John. B) :. parent(X. david). since we use the word ancestor in its own definition. parent(Y. In the first place. so prolog is left with the sub-goal ancestor(jim. parent(jim. great grandparent and so on.parent(A.B) ancestor(A. Y). grandparent. and defines with a rule when someone is someone's grandparent (if he's a parent of that person's parent). it uses ancestor to define ancestor. parent(X. B). prolog will first try line one of the definition. B). but won't be able to unify parent(steve. parent(Y. parent(Z. It . B).parent(A. it becomes complete definition. The second rule is recursive. parent(A. B). but if we were to add a fifth parent to the program. parent(nathan. so is David an ancestor of John? Here we can use the first definition. If we would write rules for all these situations we could define ancestor(A. parent(steve. Furthermore. grandparent(A. parent(A. It's not elegant. Z). B). This may work for a bloodline with four generations. The first rule is called the stop predicate as it stops the predicate calling itself. jim). X). so the question becomes. X). It shows a male line in a family tree. so that doesn't apply.• 4 Exercises  Recursive rules Consider the following program.B) ancestor(A. parent(A.B). we'd need a new line for ancestor as well. john).B) ::::parent(A. we would look at the defintions.parent(A.B) for this particular bloodline: ancestor(A. john) with any line in the database. a parent. if P is C's parent. For instance. B) :. parent(X. john). X) and ancestor(X. a lot of work and most importantly. ancestor(X. is Jim an ancestor of John? Jim is a parent of David. no matter how long.john). This doesn't sound very useful. person P is person C's ancestor. ancestor(A. but used together with the first statement. Clearly this is not the way to go. What if we wanted to define when someone is an ancestor of someone else? That is. X). It will then try the second line and come up with the sub-goals parent(steve. In prolog. To achieve this we need to think about the definition of an ancestor. B) :.
instead of a :. use: a :. john . david . or do a lot of unnecessary work. using the first line of the definition. nathan . let prolog evaluate non recursive goals first. In the example above.ancestor(nathan.  Using recursive rules Using recursive rules is not without its dangers.  Examples • A classic example of a recursive function is the factorial function. jim . It can very easily find all ancestors of John: ?. but don't do it unless you know why you're doing it. it can lead to all kinds of loops. john) which. steve . john) is true. but your program won't always be so clean and straight-forward. a. because parent(david. If you start with the recursive predicate prolog will try to search 'deeper' before seeing if it can stop recursing. The following guidelines should always be kept in mind when writing recursive rules. jim . if at all possible. . b. put the recursive rule on the right.will continue this until it's left with the subgoal ancestor(david. You can see how this is implemented in the section Math.a. Prolog is very comfortable with using recursive rules. X= X= X= X= No steve . X). For instance. is true. Always put the non-recursive predicate before the recursive predicate. john). In most programming languages. Or all people that Nathan is an ancestor of: ?. If you recurse before you've evaluated the other sub-goals. Sometimes it's necessary to put the recursive element on the left. it wouldn't actually make a difference. X= X= X= X= No david . meaning prolog has run out of memory. This is the same principle as the previous guideline. prolog could either get stuck in infinite recursions. • Avoid recursion on the left When writing a recursive rule. • Start with your stop predicate. Functions and Equality.ancestor(X. which will usually cause stack overflows.b.
PROLOG will say 'No'. something as complicated as the known universe. then telling you what the values are. and is OK. • One thing that can easily be defined recursively is a list. Prolog will then tell us: X=5040. so you might get equal(A. this is called 'nondeterminism'. The following chapter explains how. X=5 Y=f(5. The program might not go as far as to constrain the variables to have exact values. search Contents . % Explains that things are equal to themselves X is 3+2. since we usually use predicates instead of functions.Y) which is equivalent to the statement. Jump to: navigation. these two definitions exactly define anything that is a list.Z). If no values of the variables will make a solution. Together. A simple program might be X is 3+2. which took a positive integer as input. and when you run it. To end the recursion we need a second statement. You can also get a 'Yes' result for more than one value of the variables. a structure. equal(f(X. which says that a list is something that consists of an element. we would use the query ?. we will instead define a predicate fact(X. In Prolog. Lists are actually a very common structure in prolog programs. and they're used in a recursive way. "The factorial of X is Y. A PROLOG program works by constraining the variables until eventually they have particular values.you might learn recursion by writing a function fact(). search A PROLOG variable can represent anything." Then.Y). In this context we'll consider a list a collection of things (elements) that are placed in some order. Prolog/Variables < Prolog This page may need to be reviewed for quality. the result will be X=5 Yes.X). an array. for instance. To define this recursively. we'll state that a list is a single element. Prolog/Lists < Prolog This page may need to be reviewed for quality. that is followed by a list.A). a name.fact(7. to find the factorial of 7. and returned a positive integer. a number._) Yes where the '_' means that you have a variable remaining as part of the solution. Jump to: navigation.
d. a. A. like these examples.c. A.e]).d.[c1. but the tail is always another list.listsplit([a.c3]] [[A. c.3 Reversing a list 3 Exercises 4 Answers to Exercises  Lists Any language needs a way to handle collections of objects and prolog is no exception.C]. quu([a.listsplit([a. listsplit([H|T].1 The member predicate o 2. D] Most prolog code will not define a list explicitly. A list in prolog can look like this: [a. with many possible elements.e]  (an empty list) .a3].d. but rather handle lists of any length. Here. B.e].b2. List = [a. [b. and the commas separate the various elements.c. m. T).e] [a] a a [b.c2. The following program shows how to use this.e.c. c.V). d.b.a2.c. A head can be anything. Prolog will answer: A=a B = [b. here are some examples of lists. and what heads and tails they result in: List Head Tail [a.[b1. For the query ?. D] [p(A.c. b.c.e]. c. B). you use the bar notation: [Head|Tail] In this notation the variable Head represents the leftmost element of the list and the variable Tail represents the rest of the list represented as another list. C. c.d. H.b3].e]). For the query ?.2 The append predicate o 2. d._).B]. To handle lists without knowing what's inside them or how long they are. Prolog will answer yes. [H|T] is a list. V)] [[a1. from a predicate to another list. and different types of element can occur in the same list. e] The brackets are the beginning and the end of the list. e] . [b.b.listsplit(List.f]. and T is the tail. The following are examples of valid lists: [a.d. H is the head. d. p(a. but a list can contain all sorts of elements. Here all the elements are atoms.[a.b.d. a.b. e] . b.c].d.b.[hide] • • • • 1 Lists 2 Examples o 2. [B. The program can even be used to 'create' a list: ?.
instead of writing them yourself. Splitting up lists can be done with more than two heads: [H1. for it. Tail) is true. [_|Tail]) :.b. we use the anonymous variable. Tail). Note. last([_|Tail]. b. b. if X is the head of the list member(X. [a. member(X. [a. The second line says that the last element (Elem) of a list [_|Tail] is the last element of its tail (Tail). c]). [X|_]). c]). [a. The following. Builtin predicates are defined by your prolog implementation. if member(X. X=e First. Elem). member(b. List). Elem).c. The member predicate is defined like this: member(X. % ie. Where List is any prolog list. _.b. but can be used in any program.b. c]). You use it like this: member(Element. Member is a standard prolog built-in predicate. succeeds (returns 'Yes'): member(a. however that this will fail if the list has less than three elements. Now consider the following program: last([Elem]. H2. b.b]] [a. H3|Tail] This will split a list up into the first three elements.c]. It can be used as a program to find a list's last element: ?.  Examples  The member predicate Normally. and the rest of the list.  The append predicate . [a. b.last(Tail. and Element is any element in that list. These implementations are shown here to illustrate how to modify lists. member(c. there is the stop predicate. Since we don't care about the head. c]).e].b. % member(X. Will return the following values for Element: Element = a. that says that the last element of a list with one element.c [a. Element = c. [a. is that element.b]] ] Note that the empty list [ ] cannot be split up and therefore will not unify with [H| T].d.[a. [Head|Tail]) is true if X = Head % that is.% or if X is a member of Tail. Element = b. This query: ?.last([a. for instance. This relation defines the last element of a list.member(Element.X). you would use builtin predicate for these list operations.a. Elem) :.b.[[a.
b. and appending the tail of A. [a. or append(. c]. append/3 has many uses. b. 3]. 3]). ListLeft =  ListRight = [a.  Reversing a list We will look at two ways to reverse a list. e. ListLeft = [a] ListRight = [b. C. The append predicate can be defined like this: append(. Ys. c]). The first line simply unifies the last two lists.append([a. R = [e. last(List. c. Ys. Ys. b. -. (Try this for yourself to see what the result looks like).x. [a. Result = [a. Many more definitions are possible. Last) :. e] . b. ?.B. Zs).e.e.append(Xs. Right) :. ListLeft = [a. It can be used as another way to implement last/2 which was defined earlier. It's used like this: append(Xs. ListLeft = [a.split([o. c]. first of all the naive way is to simply keep taking the head off and appending it onto the end. [A. -. ListRight.o. 2. Left. Zs) Where Zs is Ys appended to Xs. c]). gives the tail of C.append(Left. append([A. in which case it would bind X = [e]. with B. Result). u. f] Or to split a list into left and right parts. Ys). A = [o. 2. c] ListRight =  . R). u. [o. [a. it concatenates two lists. x. You can use it to append two lists: ?. No You can even use it with three variables. 3]). B. Due to the nondeterminism of Prolog. b. append(. [e]). 1.c]). ?. The following succeed: append([a. in other words. The second line (the recursive clause) declares that. reverse(. append([X|Xs]. b.u]). X. 3]. b. [Last]. c]. L = [o. b.split(A. [u. Ys. b] ListRight = [c] . [Pivot|Right].u. [d. 2. [a. List).The built-in predicate append/3 attaches a list to the back of another.b. 2.append(_. o.). o]. e. u]. c. [a. c] . f]. split(List. d. b. given append(A. [a.C) the head of A is equal to the head of C. List). c] .c]. . B. 1.o]. [1. ?. [X|Zs]) :. L. e. [1. Pivot.append(ListLeft.b. C]. it succeeds for queries like: append(.e].
YsX) :. X=7. Ys. [X|Zs]) :.X).Terminating condition call(. Count.1]]. length([_|Tail]. append([X|Xs].1. Another solution which uses tail recursion optimisation and Prolog's arithmetic (And therefore uses less stack space): % 0 . Ys.length([a.Recursive rule call([H|T]. Contents . Zs).reverse(Xs. call(T.Calling Rule cl(List. % 1 . then.X). length(.Ys).1.59.Ys). Count. Ys.[X].. Out).1. Jump to: navigation.1.Ys) :.b.95.[1. Count). we will use recursion. X=4. Out) :Count1 is Count + 1.length(Tail. revappend([X|Xs]. using functions and equality.length([a. Functions and Equality < Prolog This page may need to be reviewed for quality.1.1].YsX). Zs). Zs) :. Out) :call(List. Ys).  Exercises (1) The built in predicate length() can be used to find the length of a list.revappend(Xs. Ys. For example: ?. How might this predicate be defined?  Answers to Exercises (1) As you probably guessed.0).append(Xs. 0 . Executing it means that you traverse the list over and over again appending each time. Ys. % 2 . search This section explains how to use math in prolog.XYZ.reverse([X|Xs].revappend(Xs. ?.Length) :. [X|Ys]. Out). The strategy used in revappend is called an accumulating parameter. revappend(. Length is TailLength + 1. Prolog/Math. reverse(Xs. append(Ys. Ys).TailLength). Count1. A more efficient version can be created by taking the definition of append: append(. and changing it slightly.
a(345.841471. the query ?. is a function. To perform mathematical operations on numbers. a(A) :. they've already been defined in your prolog . Functions are predicates that represent a value. will fail because sin() is implemented as function and not as a predicate. in queries.3).[hide] • • • • • • • 1 Numbers in Prolog 2 Functions 3 Equality 4 Math 5 Examples 6 Exercises 7 Answers to Exercises  Numbers in Prolog Prolog. Functions can be used anywhere a number or constant can be used.14286 ^ 4^2 16 sin sin(3) 0. When you use functions like sin(). predicates have always represented a simple true or false. in your program. we will need functions.3409857) :. The following common mathematical functions are built in to most Prolog implementations: function example result + 2+3 5 4-1 3 * 4*3 12 / 22/7 3. Numbers are used like constants. we will need to look more closely at equality. for instance. if the fact p(0).b(A.b(23476. is in your program. predicates and rules. will unify with it. the following are valid ways of dealing with numbers in a predicate: a(12. Predicate a(A.14112 (table to be completed) Note that functions themselves cannot be evaluated. the query ?p(sin(0)). sin(0) represents the value 0 and sin(1) represents the value 0.sin(3). The sin() predicate. has a representation for numbers. B) is true or false. and represented like they are anywhere on the computer. 234. To store the result of a mathematical operation in a variable. depending on the values of A and B. 345).923804).  Functions Until now. like any other programming language. One difference between functions and predicates is that the meaning (or definition) of a predicate is usually defined by you. For instance.
but for now. with slightly different meanings. The is operator is meant specifically for mathematical functions.Bx). When working with functions. plus(A. This predicate adds two numbers (A and B). Ax is A .  Math Now that we know about functions and equality. In other words. A = 22/7 Instead of assigning the result of the operation to the variable A.implementation.1.1). fac(A. So Prolog will answer: A = 3.B) :A > 0. This query assigns the result of mathematical operation 22/7 to the variable A. If you ask ?.  Equality There are several kinds of equality.14286 This idea may be familiar from other programming languages. fac(0. because Prolog will compare a number (1) to a formula (2-1). rather than to the result of solving the formula. You'll get "Yes". we will almost always use the is operator. It doesn't solve the right-hand side. B. So you get this: ?. but that's something you will usually not need. . But if you ask ?. we can start programming with math. prolog will not find the definition in your program. prolog assigns the operation to A. The = operator is used for unification of variables and can be used with any two arguments (although it will fail if the two arguments aren't the same and can't be made the same by instantiating variables a certain way).(1 is (2-1)). however. without evaluating it. C) :. First. and unifies the result with C. The = operator. but instead keeps it as a formula. but in it's library of built-in predicates. is very different.(1 = (2-1)). look at: ?. The following program is somewhat more complex.A = 22/7. B is A * Bx. It is possible to create your own functions. The left argument has to be a variable and the right argument has to be a mathematical function with all variables instantiated. You can see the same thing with queries. Here we will just look at the = operator and the is operator. You'll get "No".C is A + B. these two will suffice.A is 22/7. because the (2-1) is evaluated (solved). This program calculates the factorial of A (A! in math notation). Prolog knows many other ways of comparing two terms or instantiating variables. fac(Ax.
B. B is A * Bx. fac(Ax. X=0.X = 1 + 2 + 3.-2.9. and explain why the program is set up like this.5. (3) The factorial program shown at the end of this chapter sins against one of the guidelines of using recursive rules. In the second rule: fac(A.N) is true when N=A+ (A+1)+(A+2)+. fail.fac(3. Ax is A . fail. What would prolog do after it had found an answer. The second states that the factorial of a number A greater than 0 is the factorial of A-1 times A. Explain why the line A > 0 is necessary. fail. Y is X.. The recursive part is not the last predicate in the rule. The first rule states that the factorial of 0 is 1.B) :A > 0.  Examples  Exercises (1) What will prolog answer to the following queries (on an empty database)? Try to think of the answer yourself. (2) Write a predicate called sigma. You may assume that A and B are integers with B>A.sigma(4.sigma(-7. • • Show how prolog evaluates the query ?. such that sigma(A. X + 3 = Y.. .Bx).X). Test your predicate with queries such as: ?.X).X is (14 + 16)/3. if the line was missing?  Answers to Exercises .X = 1000/100 + 5. • • • • ?.X). ?.X is 100/10. X). X = -27 . ?. In other words.1. ?. ?.+(B-2)+(B-1)+B.sigma(-5. and then use a prolog compiler to verify it. X = 39 . ?.It works recursively.
5 Atomic Sentences o 1.B. Prolog/Putting it Together < Prolog Jump to: navigation. These rules are loaded into the compiler. sigma(A1.2 Variables o 1. search This section serves both to combine the knowledge from the previous chapters and to review it.B.A). The compiler will try to prove that the query is true.or first order logic). and then a small program is presented that combines the knowledge from the previous chapters.  constants .8 Terms 2 The Prolog Compiler 3 An example program 4 Examples 5 Exercises  Prolog A Prolog program consists of a database of rules.4 Functions o 1. sigma(A.6 Sentences (and connectives) o 1.1 constants o 1. sigma(A. Everything in Prolog is described in logic (Prolog logic is variant of classic predicate. Contents [hide] • • • • • 1 Prolog o 1. Why does this happen? A1 is A+1. The user can then run queries on the database. there is more than one way to solve this problem.(2) As usual. Starting from the atoms (the smallest bits) these are the most important logical symbols that make up a Prolog program or query. Here's one way which uses recursion in a similar way to the factorial predicate.N) :B>A.N1). %What do you think would happen if you removed this line? Try it. N is A+N1.3 Predicates o 1.7 Rules o 1. Prolog is first explained in more detail.A. true to its basic structure.
For instance. Examples of valid variables: B Parent Result PredicateList023  Predicates Predicates consist of a functor (one or more lowercase characters. Examples of valid predicates: childof(Child.  Atomic Sentences An atomic sentence is the smallest part in a prolog program that can take on the meaning true or false. A constant is not made up of other Prolog symbols (it's an atom) and it does not represent anything in the Prolog world except itself. You do not assign a value to them and then use them. various values are assigned to them by Prolog when you run a query to try and make the query true. possibly followed by a number of terms between brackets. It's important to note that variables function differently in Prolog than in most programming languages.or uppercase characters. A predicate is either true or false.These consist of one or more lowercase characters. Some other Prolog statements. but instead of being false or true. starting with an uppercase letter. will return the square root of whatever number A represents. They can represent pretty much any Prolog structure. the function sqrt(A). based on its terms. it can represent anything a variable can represent. george_b) A = tan(B. such as unification (=) are atomic sentences as well. Examples of atomic sentences: childof(george_w_b. They have no meaning attached to them. Examples of valid constants: foo cd_p0345 a dirk  Variables Variables are containers. starting with a letter). Father) predicate(dog(x). cat(Y)) architect(a_vandelay) termless_predicate  Functions A function is built up the same way as a predicate. C) + D . from constants to predicates. starting with a letter. A good way to think of atoms is as the objects of the prolog world. separated by commas. Variables consist of one or more lower. All predicates are atomic sentences.
male(a).a(X).  Terms A term is any Prolog construct representing an object. Examples of rules. Queries are special types of rules. Prolog will attempt to find an instantiation of the variables that will make the query true. it will unify the variable X with the constant a. the sentence will be true if (and only if) both atomic sentences are true. b). Every sentence in a Prolog program is a rule.. female(b) A = B * 3. cat(scratchy). mouse(itchy)  Rules A rule is a special type of sentence. no :-) is called a fact and is considered true as is. female(A). car(porsche). It has a predicate on the left. mother(A) :. Atomic Sentences are of course sentences. Most sentences in Prolog are just a number of predicates with comma's between them.has_child(A). and encounters the rule a(a). Prolog will check if it's true.  The Prolog Compiler The Prolog compiler allows users to run queries on a database of rules (a Prolog program). important though they are. it will instantiate the variable X to the value a. A rule states that the predicate is true if the sentence is true. Examples of sentences. If a sentence joins two atomic sentences with a comma. given that the rules in the database are true. with no predicate before the :-. If there are variables in the rule. If the query has variables.e. Other Prolog concepts are explained in the Glossary. childof(a. and a sentence on the right separated by :-. Since a(a) is true. The most important connective in Prolog is . Sentences (and connectives) Sentences are Prolog constructions that can take on the meaning true or false. A rule with no sentence after the predicate (and thus. It's concluded by a period. indicating that all atomic sentences need to be true for this sentence to be true. Note: The other connectives. (the "and" connective). This instantiating of variables is based on the process of unification. Sentences are the lines in a Prolog program. Once a query is entered. will come up later. non-atomic ones) are comprised of atomic sentences joined together by connectives. Prolog will return X = a as a solution. Unification takes two predicates and sees if one can be used to instantiate the variables of the other. Constants and functions are always terms and variables can represent terms. If Prolog is trying to verify the query :. in the database. X). then the predicate is true for any instantiation of the variables for which the sentence is true. even(A) dog(poochie). Other sentences (i. equal(X. The following two predicates unify: . In other words.
B) q(x. A) q(x. % TailSum is the sum of the tail Sum is FirstNumber + TailSum. % Add the first number to that to get the Sum of the list. the 'head') and a Tail (the rest of the list). [y. If Prolog is trying to verify the query :. This is known as backtracking. The second two rules constitute the sum predicate. y) q(A. because two different variables can be bound to the same constant. Neither of the variables are instantiated yet (i.p(A.z. they can only be instantiated to the same value. if Prolog can't find anything in the database that makes d true. B = y As do these: q(A. Yes . Prolog will return X = c as a solution to the original query. B = [y. -2]).. It sums the list. x) This is because A can be x or y. If d succeeds.sum_is_zero([1.C]) q(x. but not both. and checks if it's equal to zero.e. TailSum).  An example program The following program checks if the sum of a list of numbers equals zero: sum_is_zero(List) :sum(List. The first rule is the stop predicate. and encounters the rule b(A) :. Prolog will now add c(A) to its list of queries to verify. it will (temporarily) instantiate A with c.sum_is_zero([1. B) unification: A = x. and adds the first number to the sum of the tail. y) p(z. Sum). The first rule in the program is pretty straightforward. Sum) :% The list is split into its first number and its tail sum(Tail. It simply states that an empty list has a sum of 0. Sum = 0. using the sum predicate.z. Yes ?.c(A).d. sum(. in the database. It will unify the variable X to the variable A. Prolog will forget this rule and try to make c(A) true some other way. B) unification: A = z. These on the other hand: will unify. 0). -1]). % Sum is the sum of the List % Sum needs to be 0 % the sum of an empty list is always 0 (stop predicate) sum([FirstNumber|Tail]. The second rule first splits its list into a FirstNumber (the first number in the list. 1. and try to verify d.b(X).C] However. It calculates the sum of the tail recursively. If it encounters the rule c(c) :. these will not unify: q(A. Some queries: ?. have values assigned to them) but they are bound to each other.
Contents [hide] • • • • • • 1 The cut 2 Using Cuts 3 Negation 4 Cut-Fail negation 5 Examples 6 Exercises  The cut Consider the following program. c) 4 r(D.b. c(martha.66862 . doug) 2 dog(A) dog(B) 3 f(X. explain why not.5.5.383724]. a :. A = 4. 42).7849. P) child_of(martha. . b.?.sum([-1. 1 child_of(M. Z) f(a. give the instantiation of the variables. if they don't. e.c.d.7849. 3. 2. A).383724]. 3. the way negation is used in Prolog and a useful combination of both. No ?. 2. No  Examples  Exercises (1) Which of the following predicate pairs unify? If they do.sum([-1. c :. d. F) r(p. D)) Prolog/Cuts and Negation < Prolog Jump to: navigation. search Programming | Prolog | Cuts and Negation This section explains the use of cuts to control backtracking. b :. Y.
When Prolog starts out on the query it tries to prove a(Q. !. backtracks again and tries b.b(X). c(3). b(2). if it has chosen frank for the variable X and encounters a cut. Y) :. It finds a rule for c and now needs to prove d. because it couldn't prove it. b(3). If Prolog finds a cut in a rule. If we ask Prolog ?. whereas it returns all alternatives for R. R). and terminates. R). When user presses . and tries to prove c in a different way. you can use the cut operator: !. To understand how the cut changes the meaning of a program. R). Q=1 R=3. Prolog will consider frank the only option for X. To control the way Prolog evaluates your program. so Prolog adds the goal b to its list. using the first line of the program. so it can still look for alternatives for R. Prolog can't look for alternatives for Q. If you load this into Prolog and ask Prolog ?. To prove this rule. even if there are other possibilities in the database. This is illustrated by the following program a(X. b(1). Remember.. Prolog now removes the goal d from its list. The first rule states that a is true if b is true. it will not backtrack on the choices it has made. It continues with the last goal of the rule. And when we ask Prolog for more answers.b. It first finds R = 1. using the last line of the program and Prolog terminates. Prolog will evaluate it by first searching for any rule that can make a true. Prolog can't prove c either. it will first answer ?. As you can see Prolog considers 1 as the only option for Q. Prolog first checks for alternatives to the goal c(R). c(R). d(X).a. consider the following: . c(Y). When it runs out of alternatives for R. c(2). it succeeds with Q = 1. it adds a to its list of goals to prove. Then Prolog encounters a cut and sets Q = 1 as the only option for Q. and completes its goal. !.b(X). the cut operator is an atom. This is known as backtracking. which fails. It can prove this. c(X).. and can be used in the following way: a(X) :. Understanding how Prolog evaluates your query is essential in Prolog programming. No .a(Q. using the . c(1).-key: Q=1 R=2. Q=1 R=1. when Prolog encountered the cut it hadn't chosen an instantiation for R yet. it needs to first prove b(Q).a(Q. For instance.
if we ask Prolog a(2). If the line b(4). b(2). b(4). It then encounters a cut. Now. the query ?. however not(X) does not mean that X is false. it is forced to ignore all alternatives to a(Q). To prove the goal.b(X). b(1). Prolog will not consider the second rule. a(X) :. because the user has specified it.a(X) :. will return yes. before it encounters the cut. using X =4 and the last line of the program. b(3). allowing Prolog to prove c(2). However. will fail for the query ?. This time. With the cut Prolog fails to find an answer. The cut also works across multiple rules. c(X). is removed from the program. it would have found that Q=2 makes both b(Q) and c(Q) true. it will return yes. If it could have searched for alternatives. it first proves b(Q) with Q = 1. d(4). and Prolog encounters a cut in that rule. When it tries a(4) with the first rule. b(1). woman('Eve'). c(3). it succeeds in proving b(4) and reaches the cut.d(X). and Prolog has to terminate. with the database: man('Adam'). it means that X can't be proven true.b(X). !. !. and is allowed to solve the query with the second rule. If a program has two rules for the goal a(X). For example. c(X).. and when Prolog reaches the cut X becomes committed to 2. because Prolog still reaches the cut. Prolog could solve the query with the second rule.a(Q). but also to that rule for a(X). but Prolog tries the first rule first and when it encounters the cut. For instance. Prolog instantiates the X in the first line of the program with 2. Prolog would return Q = 2 to the query ?.  Using Cuts • • • examples where cuts are necessary if-then-else structures advice on using cuts (red cuts & green cuts)  Negation not(X) is the way to implement negation in Prolog. . which fails. Without the cut in the first line. Prolog fails on the first rule. the following program: a(X) :. but the cut doesn't allow that. c(2). it is not only committed to the instantiations of the variables. is committed to Q=1 and can't find a proof for c(1).a(X). asking not(man('Abel')). It then tries c(4).a(4) will fail too.
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview.