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

Doug Arnold doug@essex.ac.uk

1
• • • •

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.

1.1

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 Cliﬀs, N.J.,

1.2
1.2.1

Examples
Factorial

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

1

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 ﬁrst 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 uniﬁed. capital(edinburgh).3 Uniﬁcation When two terms match. when a variable is uniﬁed with another term it is said to be bound to that term. More generally. Predicates can be speciﬁed 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 eﬀect it becomes that term. Note: terms with functors with diﬀerent arity can never match. _ ). • a variable matches anything. it is the most speciﬁc term that matches both. loves( kim . The following involve diﬀerent predicates: capital(scotland. so arity is as important as spelling. the uniﬁcation of two terms is the term that ‘combines the information from both’.sam) loves(leslie. • two compound terms match iﬀ: – 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 uniﬁed. 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 uniﬁcation of variables has to be ‘consistent’ in the sense that one variable cannot get two diﬀerent 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 uniﬁed. Query 7 ?. backtracking occurs — we begin searching the database again starting where we left oﬀ 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 ﬁles. Note: to consult a ﬁle either pose a query with either (i) the predicate consult/1. author(deighton._). or (ii) the name of the ﬁle in square brackets. 4 Using Prolog Prolog is an interpreted language. The user: • creates databases (using a normal text editor) which are stored in ﬁles.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 ﬁle name as argument. Query 6 ?. • consults the ﬁles (‘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 ﬁle 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 ﬁle 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 ﬁle.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 identiﬁer is the current goal.pl” extension oﬀ: | ?.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 ﬁles 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 ﬁle. i. so you can miss the “. It is worth remembering that some Prologs require that your ﬁle 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 ﬁnd out what is in the Prolog database.listing(author/2).author(rendell. You get back a ‘yes’ or ‘no’.e. ?. but you get diﬀerent answers from what you expect – use the trace (debugging) facility. read in clauses from the ﬁles. If the program seems to be taking too long to do anything. | ?.3 Queries Normally. You will have to look at your ﬁle 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 ﬁrst 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 “/*”.