Logic programming languages and tools. Programming languages versus logic programming


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

Properties: we cn ssign properties to individul entities for exmple fred would hve the property of being crnivore properties look like C function cll the nme of the property then the entity tht hs tht property is given in brckets e. Reltionships fcts: we cn ssign reltionships between entities for exmple fred ets met or wilm ets vegetbles reltionships in Prolog gin look like C function cll we give the reltionship nme first then in brckets the two entities tht re relted e. etswilmmet etswilmvegetbles. For exmple rule...



33.5 KB

0 чел.

Lecture 10. Logic programming languages and tools. Part 2.1

10.1 Programming languages versus logic programming.

In a logic programming language, the programmer does not identify the computations or functions necessary to derive an answer. The great advantage of a declarative language is that the programmer only needs to supply the information that is known (facts and rules), and ask questions - not worry about the ways the rules must be applied to answer those questions. From a programmer’s perspective, this is a much more high-level approach to problem solving than in imperative or functional languages.

Drawbacks of logic programming:

  •  The query process can be quite slow and inefficient
  •  The programmer must supply sufficient facts
  •  Rules to allow the engine to answer the queries
  •  The programmer must understand how to phrase the facts, rules, and queries

10.2 Prolog

Prolog (PROgramming LOGic) (1972) was the first widespread formal logic language. It is a non-procedural, goal oriented language. Computation takes place by trying to infer the response to queries through accessing a database of facts and rules. The user supplies the facts, rules, and queries (expressed in predicate calculus), while the computer carries out resolution to try and infer the replies.

By far the dominant logic programming language is Prolog, so that is the language we will examine in some detail. Prolog is based predominantly on the Horn clause,

A :- B, C, D, ...

This tells us A is true if B is true and C is true and ... etc. It does not tell us the circumstances under which a is false.

In fact, in Prolog all the queries are expressed like yes/no questions, and the answers come back either as

  •  a simple “No” (meaning no way could be found to make the query true), or
  •  “Yes”, plus all the ways in which the query could be made true.

10.2.1 Core components

The basic elements of a Prolog program are:

1) Entities: terms, constants, atoms.

2) Variables: as with more traditional programming languages, we can declare a variety of variables in Prolog.

3) Properties: we can assign properties to individual entities, for example fred would have the property of being a carnivore properties look like a C function call - the name of the property then the entity that has that property is given in brackets, e.g. carnivore (fred), or food (vegetables).

4) Relationships (facts): we can assign relationships between entities, for example fred eats meat, or wilma eats vegetables relationships in Prolog again look like a C++ function call, we give the relationship name first, then in brackets the two entities that are related, e.g. eats(wilma,meat), eats(wilma,vegetables).

5) rules: we can establish rules that describe how one relationship or property is true if some other properties or conditions are true. For example, a rule could state that if someone eats meat and they eat vegetables then they are an omnivore.

Rules in Prolog have three parts:

  •  The result: this is the relationship or property which results from the rule, and goes on the left hand side of our rule, e.g. omnivore(Individual).

Note that the entity here will usually be a variable.

  •  The “if” symbol: symbol “:-” separates the result from the clauses.
  •  The clauses: the set of relationships and properties which determine if the rule is to be applied, this goes on the right hand side of the rule.

There are several logic symbols which can be used in the right hand side:

  •  The comma represents logical AND
  •  The semi-colon represents logical OR
  •  The word NOT in some ways functions like logical NOT

10.2.2 Creating a Prolog program

Creating a program in Prolog starts with creating the set of properties, relationships, and rules. Typically we will enter these into a text file ending with the extension “.pl” (e.g. “test_prog.pl”). Then start Prolog and load our database from the file. Next, begin issuing queries based on the loaded information. From this point on, everything you type is treated as a query, not a new fact or rule. For example, eats(fred,vegetables). is now asking whether or not Fred eats vegetables, not stating it as a new fact.

Syntax note: all statements of properties, relationships, rules, and queries must end with a period - the Prolog interpreter will not regard any of the above as completed until you enter a period.

Example: Create a file, called flint.pl, containing the following facts and rules:







carnivore(Individual) :-


omnivore(Individual) :-eats(Individual,meat),eats(Individual,vegetables).

food(Thing) :- eats(Individual,Thing).

Once that is created, we can load the database of facts and rules from the file, then begin issuing queries and getting answers.

In the example below assume > is the prompt:


flint.pl compiled









Individual = wilma


10.2.3 How queries are answered

Suppose we are given the query “is fred an omnivore?”


In trying to solve this query, Prolog does the following:

 search for all the relationships which match the goal, i.e. everything in our database that begins with omnivore(...)

 if we encounter a fact in our database that explicitly states omnivore(fred). then we can quit and return Yes as soon as we encountered it.

 if we encounter a rule of the form omnivore(...variable...) :- ... then we can say fred is an omnivore if we can substitute fred for the variable (throughout the rule) and still satisfy all the clauses on the right side of the rule.

In the case of our example, the rule with this form is

omnivore(Individual) :-

eats(Individual,meat), eats(Individual,vegetables).

and after substituting we want to check

if eats(fred,meat) AND eats(fred,vegetables).

Thus we have two new goals to try to satisfy to check out this rule, and we begin searching the database for facts and rules beginning with eats(...), trying to substitute “fred” and “meat” into the rules to continue the query.

If we cannot prove eats(fred,meat) then that clause fails, and hence the rule fails as well, so we must continue on checking for other facts/rules defining omnivores. As soon as we satisfy one of the facts or rules that prove fred is an omnivore we can stop and return “Yes”. If we go through all our facts and rules and cannot prove fred is an omnivore then we return “no”.

Another example. Suppose our database is:



cloudy(Day) :- rainy(Day).

Again, let us make the query:


In this case, the first applicable rule (i.e. that has cloudy as a head and one parameter) is:

cloudy(Day) :- rainy(Day).

Because Day is a variable, and we are looking for the specific value today, we can instantiate the variable Day with the value today, giving us the rule:

cloudy(today) :- rainy(today).

From this point the process continues by trying to satisfy subgoal rainy(today) and succeed because of the applicable fact in the database.

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


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

82764. Білінгвізм як психолінгвістичний феномен 43.01 KB
  Двомовність привертає увагу лінгвістів, психологів, педагогів відповідно до динаміки когнітивних підходів до опису мовних явищ та мовленнєвих процесів. У вивченні й оволодінні іноземною мовою надзвичайно велику роль відіграють різноманітні нейро- та психолінгвістичні аспекти.
82765. Типическое и индивидуальное в образах Онегина и Ленского 38.77 KB
  Цели: Формировать у учащихся представление об эпохе, в которой жил и создавал свои произведения А.С. Пушкин; Раскрыть причину недуга времени - равнодушия, разочарования во всем; Воспитывать чувство прекрасного и уважение к русской культуре.
82766. Давление и сила давления 67.5 KB
  Как вы считаете какие задачи нам нужно решить что нужно узнать о давлении чтобы разгадать всю тайну Учащиеся называют что нужно узнать о давлении что такое давление чем оно характеризуется от чего зависит как его рассчитать где применяется.
82767. Царство Грибов. Плесневые грибы 40.08 KB
  Дидактическая цель: Создать условия для осознания и осмысления блока новой учебной информации средствами критического мышления. Тип урока: комбинированный( изучения нового материала и первичное закрепление); Методы обучения: частично – поисковый, репродуктивный...
82768. С любовью на все времена. Ко Дню 8 Марта 41 KB
  Без солнца не цветут цветы без любви нет счастья без женщин нет любви без матери нет ни поэта ни героя. Горький Ведущий что может быть на свете священнее имени матери Человек еще не сделавший ни одного шага по земле и только только начинающий лопотать неуверенно и старательно складывает...
82769. «Literary quiz». Внеклассное мероприятие для учащихся 9-ых классов 28.43 KB
  Выбор темы внеклассного мероприятия по английскому языку обусловлен ее актуальностью и местом в системе уроков английского языка. Время проведения мероприятия: 40 минут Место проведения: кабинет английского языка. Содержание и методика мероприятия: учащиеся делятся на две команды соответствующие...
82770. Русский лес. Иван Соколов-Микитов. Е. Баратынский. Где сладкий шепот… 299.5 KB
  Цель: учить выразительно читать, оценивать качество чтения и содержание прочитанного, находить нужные части содержания; развивать речь, чувство прекрасного, эстетический вкус и художественное восприятие; воспитывать бережное отношение к природе.
82771. Твоя домівка 196.5 KB
  Підручник з основ здоровя ноутбук проектор екран слайд-шоу фрагменти з мультфільмів виставка Візитна карточка моєї домівки. Тож і ми часу не гаймо Урок основ здоровя починаймо. Повторення вивченого Мозковий штурм Що ви зробили сьогодні зранку щоб бути здоровими Що зробите для цього ввечері...
82772. Овочі і фрукти, молочні продукти, їх значення для росту і розвитку 774 KB
  Вчити учнів розпізнавати корисні і шкідливі продукти харчування пояснити чому дітям потрібно вживати овочі фруктимолочні продукти щодня; пояснити значення харчування для здоров’я; виховувати свідоме ставлення до свого здоров’я. Сюжетні малюнки: овочі фрукти молочні і мясні продукти тістечка цукерки торти...