LG419/519 Prolog and NLP Basics, Syntax and Semantics, Using Prolog

Doug Arnold doug@essex.ac.uk

• • • •

Prolog Basics

Prolog is: a general purpose programming language, which implements an idea about Programming in Logic, in which it is very easy to write grammars for Natural Languages, and with which it is relatively easy to implement Natural Language Processing (NLP) systems, i.e. systems for ‘understanding’ Natural Languages.

Prolog is a language – it has a syntax and a semantics. Bear in mind too that learning a language (human or computer) involves: 1. study and understanding; and 2. practice (practice, practice, practice) — using it.


The course motto
“Remember, if you don’t understand something right away, don’t worry. You never learn anything, you only get used to it.” Laurent Siklossy (1976) Let’s talk LISP, Prentice-Hall, Inc., Englewood Cliffs, N.J.,



The following computes the factorial of a number N (i.e. N!), e.g. 4! = 4 × 3 × 2 × 1 = 24. Example 1 factorial(0,1). factorial(N,FN) :N1 is N-1, factorial(N1,FN1), FN is FN1*N. Query 1 | ?- factorial(5,What). What = 120 ? yes 1.2.2 Adding Up a list of numbers

Example 2


human(socrates).s([the. yes 1.addup([].2.s(S.np.2. vp.toy]. Query 2 addup([4.2.0). det --> [the].baby.baby. v --> [saw].human(X).3].saw.baby] ? . addup([X|Xs].baby] ? . n --> [toy].baby.the.M).4 Parsing The following is a Prolog program which will parse (or generate) the sentence the baby saw the toy (etc.n.What).baby.[]). np --> det.) Example 4 s --> np. S = [the. Socrates is human. What = 9 ? yes 1.[]). vp --> v.saw.the.baby] ? yes | ?.saw.s(S. S = [the.saw.toy] ? .the. S = [the. N is M+X. S = [the.N) :addup(Xs.saw.the. yes | ?.the.toy. S = [the.toy] ? .mortal(socrates).toy. Therefore: Socrates is mortal Example 3 mortal(X) :. Query 4 | ?. n --> [baby].3 Logical Reasoning The following implements the syllogism: For any x is mortal if x is human.the.[]). no 2 . Query 3 | ?.saw.

[])))) Some non-terms: hello Sam hello-sam f(a. 1 In 3 . or predicate (any atom).t(b. and ending with a “. and – a sequence of terms. 2. b) 1(a.1 There must be no space between the functor and the left bracket.X.hello(sam))) t(a.b) X(a. These are called arguments of the predicate. Examples: a=X. • a variable is a sequence of alphanumerics.2 • • • • Prolog Syntax Prolog expressions are called terms. and separated by commas.t(d.5 Examples hello sam hello_Sam ’Hello’ _ ’1a’ _hello hello(X) f(a. • a compound term consists of: – a functor. their arguments.1 Clauses One kind of term is particularly important: Clauses.b) 2. c ) foo Hello Sam ’hello’ ’Hello Sam’ a1 X _234 f(a) f(hello.0. starting with an uppercase. A clause is a collection of terms.b) hello(1. enclosed in round parentheses. fact. or “. some functors can be written between. variables that start with _ are called anonymous. These are called operators can can be ignored for the moment.Sam) f(f(a). or – anything at all enclosed in single quotes (“’”).” (fullstop). and possibly including “_” (underline). b. man :. b f a. or even after.t(c.mortal.b. separated by “. or “_” (underline).” (commas).b) Hello Sam 1a f(a. There are several sorts of term: atoms variables numbers “compound terms” • an atom is either: – a sequence of alphanumerics.hello(x.c) f( a.” (semicolons). starting with a lowercase. f (a.

e. and – a body (a sequence of Prolog terms. • a query: a clause preceded by ?-. and – a fullstop. woman(X) :female(X). woman(X) :. 2.g.edinburgh). capital(scotland..belfast).sam). and – :-. young(sam).g. clauses complex rules conjunctions disjunctions simple facts simple-queries 4 . adult(X). • a directive: a clause preceded by :-. adult(X). happy(sam). which consists of: – a head (a single Prolog term).” (fullstop).loves(kim. • a rule. separated by commas. 2..female(X). capital(scotland.Some special cases: • a simple clause: a term followed by a “. • a conjunction. e.1 Examples woman(leslie).1. or semicolons). happy(sam). The head of a clause is the first term in it.2 Syntax:Summary terms atoms numbers variables anonymous non-anonymous compound-terms lists .

More precisely.2 Examples Term1 Term2 Match? ----------------------------------------------------hello hello X Y X leslie _ leslie f(a) f(a) f(X) f(a) woman(X) woman(leslie) loves(X.1 Prolog Semantics Matching • two atoms match if (and only if) they are the same (same goes for numbers). loves( _ . loves( kim . 3. When two variables are unified. capital(edinburgh).3 Unification When two terms match. when a variable is unified with another term it is said to be bound to that term. More generally. Predicates can be specified by name/arity: capital/2.b) womna(leslie) 3. Thus. and – the same number of arguments (same arity). 5 . capital/1. they are said to share: essentially. they become the same variable. sam) loves(woman(kim). and has that term as its value — in effect it becomes that term. Note: terms with functors with different arity can never match. _ ). • a variable matches anything. it is the most specific term that matches both. loves( kim . The following involve different predicates: capital(scotland. so arity is as important as spelling. the unification of two terms is the term that ‘combines the information from both’.sam) loves(leslie. • two compound terms match iff: – they have the same functor.3 3. it is not possible to unify X with both a and b (at the same time).edinburgh). they can be unified. S) hello x f(X) woman(X) goodbye leslie f(a. and – corresponding arguments match. Intuitively. leslie ).Y) loves(woman(X). leslie ).

Y) loves(leslie. • rules are compound clauses. The user can access the database by queries or goals (which are simply clauses). author(dickens.b) -----f(a.demon_in_view).b) womna(leslie) *fail* *fail* *fail* *fail* loves( woman(X) ._) f(a.tree_of_hands). sam) loves( woman(kim). 6 .b) -----f(a.4 Examples Term1 Term2 Unification ----------------------------------------------hello hello hello X leslie leslie X f(a) f(a) f(X) f(a) f(a) woman(X) woman(leslie) woman(leslie) loves(X. author(alcott.X) f(a.sam) loves(leslie.5 Prolog Programs A Prolog program consists of a database of facts.3.5.b) -----*fail* But anonymous variables are special (they are called anonymous because their names don’t matter): f(_. author(rendell. author(rendell.pl % author(Name.bleak_house). and rules.sam) Notice that matching and unification of variables has to be ‘consistent’ in the sense that one variable cannot get two different values: f(X.b) 3.1 A Simple Database Program 1 % authors. of the form head :.sam) hello x f(X) woman(X) goodbye leslie f(a. S ) ---------------------loves( woman(kim). • facts are simple clauses.little_women). Book).b) f(X. consisting only of a head. 3.body.Y) f(a.

• the head of the clause and the query are unified. Query 7 ?. backtracking occurs — we begin searching the database again starting where we left off before. the user typically interacts directly with Prolog.berlin_game). • starts Prolog.author(X.author(W. Instead. before using them).author(X. some results are returned. Prolog solves (answers) queries roughly as follows: • the database is searched from top to bottom until a clause if found whose head matches the query.author(deighton.author(deighton.london_set). – types queries. % authors. 7 . i. • if a solution cannot be found to a sub-goal. (no need to compile files. Note: to consult a file either pose a query with either (i) the predicate consult/1. author(deighton._). or (ii) the name of the file in square brackets. 4 Using Prolog Prolog is an interpreted language. The user: • creates databases (using a normal text editor) which are stored in files.X). File names must be atoms.pl ends here ---------------------------- Query 5 ?. • is the clause has a body then each member of the body is treated as a new sub-query (sub-goal) to be solved. Query 8 ?. etc.mexico_match). and the file name as argument. Query 6 ?. • consults the files (‘loads’ them into Prolog). and – whose answers Prolog displays (prints).e.london_set). which – Prolog solves (answers).X).Book).Y) Query 9 ?.author(X. author(deighton. • if the clause is a fact then we have success. writer(X) :author(X.

1 #9: | ?. mexico match).author(X. where file is an atom – the name of the file containing your program..X). | ?. yes | ?. Book = demon in view.[file].An Example Interaction SICStus 2. e. demon in view). author(dickens. 18 msec 1104 bytes yes | ?. 09/03/95 4. Book = little women.pl’].pl consulted. X = berlin game ? . author(rendell. ).2 Loading a file To the Prolog prompt (?-) type: | ?. Book = tree of hands. X = rendell ? . author(rendell.pl’]. author(alcott. X = london set ? . X = mexico match ? .[’authors. author(deighton.[’myfile. no | ?..g. no | ?. | ?. author(deighton. bleak house). little women). type “sicstus”: % sicstus 4.X). author(deighton. X = berlin game ? yes | ?. berlin game). consulting authors.pl’].[’myprolog_progs/myfile.pl. X = alcott ? yes | ?. tree of hands). X = rendell ? .halt.author(X.Book).author(deighton. 8 .1 Starting Prolog In an xterm or decterm window. london set).author(deighton.listing. writer(A) :author(A.X). authors.

listing(foo/2 ). If you only want to see one predicate (say author/2). as currently instantiated 9 . and put them in the database (asserting them).X).These cause Prolog to consult the file.listing. it may be in a loop – try typing CTRL-C.listing(author). ?.5 Semantic Errors Your program loads okay.trace.pl”. 4._35) ? Here: ? 23 the rest means the tracer is waiting for you to tell it what to do is the invocation identifier is the current goal.pl” extension off: | ?.e. and if your query contains variables (other than the ‘anonymous’ variable “_”) an indication of the values they have when the query succeeds.listing(foo). You are then shown stages of the computation. Simply type the queries: | ?. ?. Sicstus expects Prolog files to end with “. You can get alternative solutions by typing “. You start the debugger by typing: | ?. This gives you everything.[myfile]. When there are no more solutions. Often you will get ’syntax error’ messages when you consult (load) a file. i. so you can miss the “. It is worth remembering that some Prologs require that your file ends with a blank line. print all the clauses currently in the database print all the clauses currently in the database for the predicate foo. then: | ?. you will get the answer “no” (i.4 Syntactic Errors. what you want to do at the keyboard is to solve queries (goals). type “listing”: | ?.listing. 4.” (a semi-colon). If you want to find out what is in the Prolog database.listing(author/2).author(rendell. You get back a ‘yes’ or ‘no’.e. ?. but you get different answers from what you expect – use the trace (debugging) facility. read in clauses from the files. If the program seems to be taking too long to do anything. | ?.3 Queries Normally. You will have to look at your file and try to work out what they mean. like the following: 23 6 Call: author(rendell. with any arity print all the clauses currently in the database for foo with arity 2 4. no more solutions).

This involves the learing about the following: logging on Windows How to move. and what is not in.At this point you have several options (not all will make sense yet) h RET s r l get help ’creep ’ to the next goal skip: at a Call or Redo port.6 Stopping Prolog (exiting) To exit Prolog. etc. f(a. % part of this line is a comment.b). a comment */ 5 5. it is useful to bear in mind that Prolog allow allows comments – these are bits of text that are simply ignored by Prolog: • Anything on a line after “%”. 4. windows.1 Exercises Basic Exercises The first task is to get to know how the machines in the Computer Lab work. raise. lower. % This is a comment % on several lines. the tracer skips to the end (Exit or Fail port) of this invocation retry – go back to the Call port of this procedure leap – go to next spy point 4. Examples: % This whole line is a comment. %% This is a comment too.7 Comments When creating Prolog databases.halt. type: | ?.it is a good idea to indent things so you can see what is in. /* This comment goes on for several lines -. 10 . and • Anything between “/*” and “/*”.

5 Mail You must learn how to: read mail messages write mail messages send mail messages save all or part of a mail message to a file Exercise 5.ac.3 The file capitals. Consult it (i. read files (cat.ps extension are PostScript files which can be printed on a PostScript (i. Exercise 5. load it into the Prolog database). and generally try things out as described on the handout under ‘Using Prolog’.4 Emacs For Emacs (or whatever other editor you propose to use) you should find out how to start it up (click on the Text/Graphics menu item on the menu bar at the top of the screen). You should learn how to print files to both laser printers and line printers.capital(X.essex.pl contains a simple prolog database. and learn about commands to make directories (mkdir).5. rename and move files (mv).el extension contain emacs code Files with . 5.e.pl extension contain Prolog code Files with . ?. Internet Explorer You can use Netscape or Internet Explorer for getting soft copies of files (programs and handouts) across the network. or 5. try some queries.Y). You should go to the lg419 directory (http://clwww. enlarge the window it appears in. If you are using another editor. list files (ls).3 Netscape. ?. and a few other basic things.1 Use emacs (or whatever) to make some of the editing changes suggested on the first handout. change directory (cd). 5. more). (Don’t type it in by hand) 5. 11 .X). Exercise 5. and run the tutorial (see the help menu at the top of the emacs window).uk/course/LG419/) and look at the documents that relate to this course: Files with . Save this file from the LG419 WebPage to your own directory.6 Prolog You should start up Prolog in a xterm or Emacs window. you do not need to do this. load a file.atlanta).e. and type commands to find out what are the capitals of various American states: ?.2 Unix Xterms (xterms) – where you type normal Unix commands. and including the text of this handout.capital(alabama. laser) printer.2 Send me a mail telling me that you are on this course.capital(X.

juneau).essex. What does this rule mean.8 The file http://clwww. Titles (etc). [’Duke’. who all the Labour prime ministers have been when Churchill was prime minister Exercise 5.pl file contains facts like the following.pl contains a Prolog database with some syntactic errors in it.g._). and the following single rule: author(deighton. capital(colorado.4 Extract the code fragments from the first hand out to do with factorials. and write prolog queries to find out: • • • • when John Major came to power.little_rock).City) -where City is the state capital of the US state State capital(alabama. Load this file. etc.uk/course/LG419/Programs/ contains a file league_table.denver). capital(alaska.7 The directory http://clwww. consult it.. capital(arkansas. pm(’Portland’. The arguments are: FamilyName. intuitively? Exercise 5. 1783). capital(california. StartDate. e. Use it to find out (via Prolog queries): • • • • How many goals Man U had conceded.5 The file errors.montgomery). Party.berlin_game). Exercise 5. lost and drawn.1 % % % % % Code Listings Capitals capitals.pl capital cities of American States: capital(State.phoenix).ac.pl which gives a snap shot of the English football league table on 6 Dec 1999.pl which contains a database of English Prime Ministers in the form of clauses for a predicate pm/5.ac. 6 6. Exercise 5. capital(arizona.6 The errors. when Thatcher left office. 12 . Which team was leading the table that day. writer(X) :author(X. Consult it.essex. and try to find and fix them. How many games they had won. and try to formulate sensible queries. see what happens.Exercise 5.uk/course/LG419/Programs/ contains a file prime_ministers. EndDate.sacramento). coalition. put them in a file. How many goals Man U had scored. capital(connecticut. 1783.hartford).of].

capital(indiana. author(deighton.london_set).capital(delaware. This line is supposed to be a comment. capital(idaho. capital(florida.carson_city). author(rendell. author(deighton. author(deighton.2 Authors % authors. 13 .mexico_match) writer(X) :author(X. Book). author(rendell demon_in_view). author(alcott. author(alcott._).bleak_house). % authors. author(dickens. author(rendell.demon_in_view). capital(geogia.3 Errors % errors.capitals. writer(X) :author(X.boise).pl % author(Name._).des_moines).pl ends here ------------------.indianapolis).’berlin game).berlin_game).little women). Is it? author(rendell.honolulul).tree_of_hands).’bleak house’).london_set. capital(nevada.pl % This file contains syntax errors: % try to find them and fix them. /*-----. capital(iowa.atlanta). capital(illinois.dover).pl ends here ---------------------------- 6.little_women).*/ 6.mexico_match). author(deighton. author(deighton.tallahassee). author(deighton. capital(hawaii. author(dickens.springfield).tree_of_hands).

human(socrates). N is M+X. %% sum(List. %% examples.4 Demo Programs These are the examples from section 1. np --> det.N) :addup(Xs.M) -%% M is the factorial of N (i. ?. vp --> v.pl ends here --------------------------------------- 6.e. s --> np.1).[]).pl ends here ------------------------------------- 14 .pl -.Some simple demo Prolog programs %% factorial(N.% errors.0).[]). you need queries like ?.FN1).M).n.[]).saw.baby.Sum) -%% Sum is the sum of the numbers in list List addup([]. n --> [baby]. FN is FN1*N.np. %% examples. factorial(N. addup([X|Xs].s(X.s([the.the.toy]. vp. %% Syllogistic reasoning: mortal(X) :human(X). factorial(0. N!).FN) :N1 is N-1. ?.np(X. v --> [saw]. det --> [the]. factorial(N1. n --> [toy]. %% %% %% %% %% A simple grammar to use this.

Sign up to vote on this title
UsefulNot useful