Logic programming languages and tools


Информатика, кибернетика и программирование

User specifies the specifictions of solution nd the computer derives the execution sequence for tht solution: Let us hve irline flight informtion of the form: flightflight_number from_city to_city deprture_time rrivl_time Then ll the flights from Wshington DC to Snt Clr cn be specified s either direct flights or s flights with n intermedite stop: flightflight_number DC Snt Clr deprture_time rrivl_time or flightflight_number DC X deprt1 rrive1 flightflight_number X Los ngles deprt2 rrive2 deprt2 =rrive130 Unlike...



38 KB

0 чел.

Lecture 9. Logic programming languages and tools. Part 1.1

Logic programming language application areas include natural language processing, expert systems, specifications checking, theorem proving, and control systems (among others).

9.1 Definitions

Logic programming languages, also called declarative languages, differ substantially from the other programming languages we have discussed. Declarative rather than procedural: only specifications of results are stated (not detailed procedures for producing them). Most importantly, logic programs do not specify the execution sequence as in most in the case of other language paradigms. User specifies the specifications of a solution and the computer derives the execution sequence for that solution:

Let us have airline flight information of the form:

flight(flight_number, from_city, to_city, departure_time, arrival_time)

Then all the flights from Washington DC to Santa Clara can be specified as either direct flights or as flights with an intermediate stop:

flight(flight_number, DC, Santa Clara, departure_time, arrival_time)


flight(flight_number, DC, X, depart1, arrive1)

flight(flight_number, X, Los Angles, depart2, arrive2)


Unlike imperative and functional programming, where implementation is done using a mapping, logic programming uses relations:

  •  In imperative and functional, we say

Given a value x compute mapping(a), i.e. square(4)

  •  In logic programming, we have

Given a value x and y, determine whether x is related to y is true

Consider the relation ParentOf as follows:

ParentOf(X,Y) where X is parent of Y

ParentOf(john, Mary) - John is parent of Mary

Horn clause. Horn clause can have only two forms:

  •  headed: single atomic proposition on left side
  •  headless: empty left side (used to state facts)

A Horn clause is an IF clause and not IFF (if and only if).



Each Ai is a simple assertion of the form Ri(…) where Ri is a relation name.

Informally, this clause means that, if A1, …, An are all true, then we can infer that A0 is also true. But, we cannot conversely infer that A0 is false just because some Ai turns out to be false.

9.2 Logic Programs

A logic program is a collection of Horn clauses.

Basic elements are:

  •  Term: a constant, variable, or structure
  •  Constant: an atom or an integer
  •  Atom: symbolic value of Prolog

Atom consists of either:

 a string of letters, digits, and underscores beginning with a lowercase letter

 a string of printable ASCII characters delimited by apostrophes

  •  Statement:

 fact statements

 rule statements

 query (or goal) statements

  •  Fact statements:

 concrete relations among objects

 used for the hypotheses


functor(parameter list)

 headless horn clauses



  •  Rule statements

 a pattern of relationships among the database objects.

 used for the hypotheses ƒ headed horn clause

 right side: antecedent (if part)

May be single term or conjunction

 Left side: consequent (then part)

Must be single term

 Conjunction: multiple terms separated by logical AND operations (implied)



 Can use variables (universal objects) to generalize meaning:

parent(X,Y):- mother(X,Y).

sibling(X,Y):- mother(M,X), mother(M,Y), father(F,X), father(F,Y).

  •  Query (or Goal) statements

 It is the theorem is in form of proposition that we want a system to prove or disprove

 Same format as headless Horn


A logic program consists of a database of the following:

  •  Fact statements
  •  Rule statements

9.3 Inferencing Process

9.3.1 User query

Computation in a logic program consists of testing a given assertion (query) A. The testing of a query A can be implemented by a process called matching, satisfying, or resolution. The facts and the rules of the program are used to determine which substitutions for variables in the query (called unification) are consistent with the information in the database. If we can infer from the clauses of the program that A is true, then we say that A succeeds. Otherwise, we say that A fails. Note that this does not mean that A is false. For example, Prolog as an interpreter, prompts the user for an input query and outputs the truth value (“yes”) or falsity (“no”) of that query and an assignment to the variables of the query that make the query true (that unifies the query).

If a goal is a compound proposition, each of the facts is a subgoal. To prove a goal is true, must find a chain of inference rules and/or facts. For query Q:

B :- A

C :- B

Q :- P

Process of answering a query is called matching, satisfying, or resolution. Resolution types:

  •  Bottom-up resolution, forward chaining. Begin with facts and rules of database and attempt to find sequence that leads to goal. This works well with a large set of possibly correct answers
  •  Top-down resolution, backward chaining. Begin with goal and attempt to find sequence that leads to set of facts in database. This works well with a small set of possibly correct answers

Prolog implementations use backward chaining.

9.3.2 Query Processing

1) If the program contains a fact ‘A0’, such that A0 matches A, then we immediately conclude that A succeeds.

2) If the program contains a clause ‘A0 if A1 and … and An’ such that A0 matches A, then we proceed by testing A1 and…and An separately as (sub)queries.

a) There are two approaches:

 depth-first search: find a complete proof for the first condition before working on others (Prolog uses depth-first search)

 breadth-first search: work on all conditions in parallel

b) If all succeed, then we conclude that A succeeds. If one of the Ai fails, then we must backtrack, i.e., give up the attempt to use this particular clause and try another clause instead.

c) Only we have exhausted all clauses whose left-hand sides match A can we conclude that A fails.

9.3.3 Unification in resolution

Unification is the process of finding values for variables in propositions that allows matching process to succeed. To unify two expressions U and V, we need to find substitutions for the variables occurring in U and V that makes the two expressions identical. Generally, it is denoted by σ and written as Uσ = Vσ.

Example 1. To unify the two expressions: R1(X,John) with f(g(John), Z) bind X to g(John) and Z to John to get f(g(John), John) as the unified instance of both expressions.

If the database contains the fact ParentOf(John, Mary) then the unification of the following query:


would be


where X is substituted by John and Y is substituted by Mary.

Example 2.

There are 6 facts in the database. The fact mother(anna,peter) states that Anna is Peter’s mother, and so on. The fact father(joe,peter) states that Joe is Peter’s father, and so on.







There are 2 rules:

grandmother(X,Y) :- mother(X,Z), mother(Z,Y).

grandfather (X,Y) :- father (X,Z), father(Z,Y).

The rule grandmother(X,Y) states that X is a grandmother of Y if and only if X is a mother of Z and that Z is a mother of Y.

The rule grandfather(X,Y) states that X is a grandfather of Y if and only if X is a father of Z and that Z is a father of Y.

The goal:

?- grandfather(tom,X).

asks, whose grandfather is Tom.

According to the rule and facts the answer is


So Tom is Peter’s grandfather.

The goal:

?- grandmother(X,peter).

asks, who is Tom’s grandmother.

According to the rule and facts the answer is


So Mary is Peter’s grandmother.

Example 3. The programmer supplies a list of facts and rules:


  •  Eagle has feather.
  •  Eagle has beak.
  •  Eagle has two legs.
  •  Betty eats vegetables.
  •  Chicken eats seeds.
  •  Chicken has two legs.


  •  If someone eats meat then it is a carnivore.
  •  If someone has feather then it is a bird.
  •  If someone eats X then X is food.

Finally, the programmer can ask questions based on those facts and rules, such as:

  •  Is eagle a bird?
  •  Is chicken a bird?

The language engine then tries to apply the rules to answer the questions, e.g.:

  •  Yes (meat is a food).
  •  Yes (eagle and chicken are bird).

Note that the answers are based only on the available information.

1 http://www.seas.gwu.edu/~bell/csci210/lectures/lp.pdf


А также другие работы, которые могут Вас заинтересовать

76380. Международная торговля, распределение доходов и экономический рост 47 KB
  Увеличение производства в отраслях ориентированных на экспорт и сокращению производства в отраслях конкурирующих с импортом. Теория Хекшера-Олина дает возможность оценить последствия развития внешней торговли для владельцев различных факторов производства рабочих землевладельцев собственников капитала и др. поскольку изменения относительных цен на товары приводит к росту вознаграждения одних факторов производства за счет других. Изменение спроса на факторы производства и доходов в краткосрочном периоде Напомним что теория...
76381. Понятие и основные характеристики конституционного строя России 35.5 KB
  Конституционный строй в широком смысле совокупность экономических политических социальных правовых идеологических общественных отношений возникающих в связи с организацией высших органов власти государственного устройства взаимоотношениями человека и государства а также гражданского общества и государства. Элементы конституционного строя РФ: 1 республиканская форма правления; 2 суверенитет РФ; 3 права и свободы личности; 4 источник власти многонациональный народ России; 5 верховенство Конституции РФ и федерального...
76383. Основания приобретения гражданства 34.5 KB
  Основания приобретения гражданства РФ: 1 по рождению; 2 в результате приема в гражданство РФ; 3 в результате восстановления в гражданстве РФ; 4 по иным основаниям. По рождению гражданство приобретается если на день рождения ребенка: 1 оба его родителя или единственный его родитель являются гражданами РФ; 2 один из его родителей имеет гражданство РФ а другой родитель является лицом без гражданства или признан безвестно отсутствующим или место его нахождения неизвестно; 3 один из его родителей имеет гражданство РФ а другой родитель...
76384. Основаяния и порядок прекращения гражданства 35 KB
  Основания и порядок прекращения гражданства. Основания прекращения гражданства РФ: 1 выход из гражданства РФ; 2 иные основания предусмотренные федеральным законодательством или международными договорами РФ. Выход из гражданства РФ свободное волеизъявление гражданина РФ. Выход их гражданства РФ осуществляется на основании заявления гражданина РФ если он постоянно проживает на территории.
76385. Основания прекращения полномочий Президента. Процедура отрешения его от должности 32 KB
  Основания прекращения полномочий Президента. 92 предусматривает несколько оснований прекращения полномочий Президента РФ. Полномочия Президента РФ могут быть прекращены досрочно: 1 по инициативе самого Президента РФ в случае его отставки; 2 по не зависящим от воли Президента РФ причинам в случае.стойкой неспособности Президента РФ по состоянию здоровья осуществлять принадлежащие ему полномочия; 3 по инициативе Федерального Собрания в случае принятия им решения об отрешении Президента РФ от должности.
76386. Администрация Президента РФ 38 KB
  Администрация формируется в целях: обеспечения реализации Президентом Российской Федерации полномочий главы государства; осуществления контроля за исполнением решений Президента Российской Федерации; подготовки предложений Президенту Российской Федерации о мерах направленных на охрану суверенитета Российской Федерации ее независимости и государственной целостности; разработки общей стратегии внешней политики Российской Федерации обеспечения реализации Президентом Российской Федерации его полномочий по руководству внешней политикой...