Prolog Tutorial

  • Prolog Tutorial
  • Prolog - Home
  • Prolog - Introduction
  • Prolog - Environment Setup
  • Prolog - Hello World
  • Prolog - Basics
  • Prolog - Relations
  • Prolog - Data Objects

Prolog - Operators

  • Loop & Decision Making
  • Conjunctions & Disjunctions
  • Prolog - Lists
  • Recursion and Structures
  • Prolog - Backtracking
  • Prolog - Different and Not
  • Prolog - Inputs and Outputs
  • Prolog - Built-In Predicates
  • Tree Data Structure (Case Study)
  • Prolog - Examples
  • Prolog - Basic Programs
  • Prolog - Examples of Cuts
  • Towers of Hanoi Problem
  • Prolog - Linked Lists
  • Monkey and Banana Problem
  • Prolog Useful Resources
  • Prolog - Quick Guide
  • Prolog - Useful Resources
  • Prolog - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

In the following sections, we will see what are the different types of operators in Prolog. Types of the comparison operators and Arithmetic operators.

We will also see how these are different from any other high level language operators, how they are syntactically different, and how they are different in their work. Also we will see some practical demonstration to understand the usage of different operators.

Comparison Operators

Comparison operators are used to compare two equations or states. Following are different comparison operators −

You can see that the ‘=<’ operator, ‘=:=’ operator and ‘=\=’ operators are syntactically different from other languages. Let us see some practical demonstration to this.

Here we can see 1+2=:=2+1 is returning true, but 1+2=2+1 is returning false. This is because, in the first case it is checking whether the value of 1 + 2 is same as 2 + 1 or not, and the other one is checking whether two patterns ‘1+2’ and ‘2+1’ are same or not. As they are not same, it returns no (false). In the case of 1+A=B+2, A and B are two variables, and they are automatically assigned to some values that will match the pattern.

Arithmetic Operators in Prolog

Arithmetic operators are used to perform arithmetic operations. There are few different types of arithmetic operators as follows −

Let us see one practical code to understand the usage of these operators.

Note − The nl is used to create new line.

Visual Prolog

  • Board index Visual Prolog

= versus := Differences between unification and assignment operators.

Unread post by Carlesius » 9 Jun 2016 1:41

Code: Select all

Unread post by Peter Muraya » 9 Jun 2016 6:46

Unread post by Paul Cerkez » 9 Jun 2016 11:54

Unread post by Carlesius » 9 Jun 2016 14:30

Unread post by Carlesius » 9 Jun 2016 15:23

Paul Cerkez wrote: Welcome back. See: http://wiki.visual-prolog.com/index.php ... ence/Facts := is the assignment operator (for facts) = is equality test if both are bound variables or assignment if one is free.

Return to “Visual Prolog”

  • Board index
  • All times are UTC

Privacy | Terms

UNSW Prolog Programmer's Manual

Arithmetic expressions, meta-logical predicates, input and output predicates.

Book cover

Prolog: The Next 50 Years pp 3–19 Cite as

Introduction to Prolog

  • David S. Warren   ORCID: orcid.org/0000-0001-7567-8156 13  
  • First Online: 17 June 2023

656 Accesses

5 Citations

3 Altmetric

Part of the book series: Lecture Notes in Computer Science ((LNAI,volume 13900))

This first chapter of the Prolog50 book is brief introduction to the Prolog programming language. It is intended to provide background knowledge that will help in the understanding of many of the papers here. It covers basic Prolog definitions, their procedural interpretation, the idea of predicate modes, bottom-up evaluation of definitions, negation including stratified and nonstratified definitions, tabled evaluation, Prolog’s use of operators, program meta-interpretation, Definite Clause Grammars, and constraints. All topics are covered only briefly, and through the use of simple examples. For each topic there is much more to be said, some of which will be said in the papers in this volume.

This is a preview of subscription content, log in via an institution .

Buying options

  • Available as PDF
  • Read on any device
  • Instant download
  • Own it forever
  • Available as EPUB and PDF
  • Compact, lightweight edition
  • Dispatched in 3 to 5 business days
  • Free shipping worldwide - see info

Tax calculation will be finalised at checkout

Purchases are for personal use only

We will see later that there may also be record structures.

Note this is a different meaning for a bound variable than in first-order logic.

See Chapter “Types, modes and so much more – the Prolog way,” in this volume.

See chapter “Ergo: A Quest for Declarativity in Logic Programming” for more on unstratified programs, and chapter “Prolog: Past, Present, and Future” for more on ASP and SMS.

Term expansion and other related facilities such as “attributed variables” have been used to add many other syntactic and semantic extensions to Prolog, such as functional programming and constraints. We discuss the latter in the following section.

See chapter “Introducing Prolog in Language-Informed Ways” for more uses of DCG’s.

See Fifty Years of Prolog and Beyond by Korner, Leuschel, Barbosa, Santos Costa, Dahl, Hermenegildo, Morales, Wielemaker, Diaz, and Abreu in TPLP 22(6).

Author information

Authors and affiliations.

Stony Brook University, Stony Brook, USA

David S. Warren

You can also search for this author in PubMed   Google Scholar

Corresponding author

Correspondence to David S. Warren .

Editor information

Editors and affiliations.

Stony Brook University, Stony Brook, NY, USA

Simon Fraser University, Burnaby, BC, Canada

Veronica Dahl

TU Wien, Vienna, Austria

Thomas Eiter

Universidad Politecnica de Madrid/IMDEA Software Institute, Madrid, Spain

Manuel V. Hermenegildo

Imperial College London, London, UK

Robert Kowalski

IBM Research, Yorktown Heights, NY, USA

Francesca Rossi

Rights and permissions

Reprints and permissions

Copyright information

© 2023 The Author(s), under exclusive license to Springer Nature Switzerland AG

About this chapter

Cite this chapter.

Warren, D.S. (2023). Introduction to Prolog. In: Warren, D.S., Dahl, V., Eiter, T., Hermenegildo, M.V., Kowalski, R., Rossi, F. (eds) Prolog: The Next 50 Years. Lecture Notes in Computer Science(), vol 13900. Springer, Cham. https://doi.org/10.1007/978-3-031-35254-6_1

Download citation

DOI : https://doi.org/10.1007/978-3-031-35254-6_1

Published : 17 June 2023

Publisher Name : Springer, Cham

Print ISBN : 978-3-031-35253-9

Online ISBN : 978-3-031-35254-6

eBook Packages : Computer Science Computer Science (R0)

Share this chapter

Anyone you share the following link with will be able to read this content:

Sorry, a shareable link is not currently available for this article.

Provided by the Springer Nature SharedIt content-sharing initiative

  • Publish with us

Policies and ethics

  • Find a journal
  • Track your research
  • prolog arithmetic examples

In Prolog, is the similar to the assignment operator = in other languages. X is 1+2 means assign the result 1+2 to the variable X. The following are some arithmetic operations performed in the prolog console window.

Search within Codexpedia

Search the entire web

  • Android Interview Questions
  • Android Development Cheatsheet
  • prolog recursive predicate/function
  • prolog function/predicate examples
  • prolog installation, hello world program and run it

web analytics

package scope
strings (end-of-line (without writing the real CR or LF character)) sprintf-like accessing n-th character
first element get the first element and remove it get the last element and remove it remove duplicates
computable tuple (these are a kind of immutable lists playing a special role in parameter passing) (1-uple) reference (pointer) (creation) reference (pointer) (dereference)
operator priorities and associativities

Creative Commons License

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Web Browser
  • Solve Coding Problems
  • What is LabVIEW?
  • What is Standard Meta Language (SML)?
  • Control Structures in Programming Languages
  • Changing row and column values of a Matrix in R Language - sweep() function
  • Program to implement Logic Gates
  • JS++ | Abstract Classes and Methods
  • JS++ | Event Handlers
  • JS++ | Interfaces
  • Difference between Swift and Objective C
  • Vectors in Octave GNU
  • How to Perform Computational Operations in Octave?
  • Java Swing | JFileChooser
  • 7 Highest Paying Programming Languages For Freelancers
  • Difference between Compile Time Errors and Runtime Errors
  • JS++ | Loops
  • How Learning To Code Can Change Your Life?
  • What is COBOL(Common Business Oriented Language)?
  • Remove Leading whitespaces from a String in R Language - trimws() Function
  • Creating First REST API with FastAPI

Prolog | An Introduction

Introduction :

Prolog is a logic programming language. It has important role in artificial intelligence. Unlike many other programming languages, Prolog is intended primarily as a declarative programming language. In prolog, logic is expressed as relations (called as Facts and Rules). Core heart of prolog lies at the logic being applied. Formulation or Computation is carried out by running a query over these relations.

Installation in Linux :

Open a terminal (Ctrl+Alt+T) and type:

Syntax and Basic Fields :

In prolog, We declare some facts. These facts constitute the Knowledge Base of the system. We can query against the Knowledge Base. We get output as affirmative if our query is already in the knowledge Base or it is implied by Knowledge Base, otherwise we get output as negative. So, Knowledge Base can be considered similar to database, against which we can query. Prolog facts are expressed in definite pattern. Facts contain entities and their relation. Entities are written within the parenthesis separated by comma (, ). Their relation is expressed at the start and outside the parenthesis. Every fact/rule ends with a dot (.). So, a typical prolog fact goes as follows :

Key Features : 1. Unification : The basic idea is, can the given terms be made to represent the same structure. 2. Backtracking : When a task fails, prolog traces backwards and tries to satisfy previous task. 3. Recursion : Recursion is the basis for any search in program.

Running queries : A typical prolog query can be asked as :

Advantages : 1. Easy to build database. Doesn’t need a lot of programming effort. 2. Pattern matching is easy. Search is recursion based. 3. It has built in list handling. Makes it easier to play with any algorithm involving lists.

Disadvantages : 1. LISP (another logic programming language) dominates over prolog with respect to I/O features. 2. Sometimes input and output is not easy.

Applications :

Prolog is highly used in artificial intelligence(AI). Prolog is also used for pattern matching over natural language parse trees.

Reference 1: https://en.wikipedia.org/wiki/Prolog

Reference 2: http://www.swi-prolog.org/

Please Login to comment...

  • Programming Language
  • 10 Best Zoho Vault Alternatives in 2024 (Free)
  • 10 Best Twitch Alternatives in 2024 (Free)
  • Top 10 Best Cartoons of All Time
  • 10 Best AI Instagram Post Generator in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

PiEmbSysTech Logo

Embedded VLSI Research Hub

Operators in Prolog Language

Introduction to operators in prolog programming language.

Hello, Prolog enthusiasts! In this blog post, I will introduce you to the basics of operators in Prolog programming language. Operators are symbols that represent predefined or user-defined predicates that can perform arithmetic, logical, or relational operations on terms. Operators can make your Prolog code more concise and readable, as well as more expressive and powerful. Let’s dive in and see how operators work in Prolog!

What is Operators in Prolog Language?

In Prolog, operators are special symbols or sequences of symbols that are used to perform operations or denote relationships between terms. Prolog allows you to define custom operators to enhance the readability and expressiveness of your code. These operators can be categorized into several types:

  • Arithmetic Operators: Prolog provides standard arithmetic operators for performing mathematical operations. These operators include:
  • + (addition)
  • - (subtraction)
  • * (multiplication)
  • / (division)
  • // (integer division)
  • mod (modulo)
  • ** (exponentiation) Example:
  • Comparison Operators: Comparison operators are used to compare values. These operators include:
  • =:= (equal)
  • =\= (not equal)
  • < (less than)
  • > (greater than)
  • =< (less than or equal to)
  • >= (greater than or equal to) Example:
  • Assignment Operator: The is operator is used for variable assignment when performing arithmetic calculations. It assigns the result of an arithmetic expression to a variable. Example:
  • List Operators: Prolog uses list operators for list manipulation. These operators include:
  • | (list construction, also known as the “cons” operator)
  • . (list tail) Example:
  • Custom Operators: Prolog allows you to define your custom operators using the :- op/3 predicate. Custom operators can be used to improve the readability of your code or to define domain-specific operations. Example:

After defining the custom operator, you can use it in your code:

  • Logical Operators (Conjunction and Disjunction): Prolog provides logical operators for conjunction (AND) and disjunction (OR). These operators include:
  • , (comma) for AND
  • ; (semicolon) for OR Example:

Why we need Operators in Prolog Language?

Operators in Prolog serve several important purposes, making them a valuable feature in the language. Here’s why operators are needed in Prolog:

  • Enhanced Readability: Operators allow you to write Prolog code that resembles natural language more closely. This can make Prolog programs easier to read and understand, especially for non-programmers or domain experts who are involved in knowledge engineering or rule-based systems.
  • Expressiveness: Operators provide a concise way to express relationships, operations, and conditions within Prolog rules and queries. This leads to more compact and expressive code that can capture complex logic succinctly.
  • Domain-Specific Language (DSL) Creation: Operators enable the creation of domain-specific languages within Prolog. You can define custom operators tailored to your specific problem domain, making it easier to work with specialized concepts and operations.
  • Mathematical Expressions: Prolog often deals with mathematical expressions in various applications. Operators for arithmetic operations (+, -, *, /) and comparisons (=:=, ==, <, >, =<, >=) allow you to write and evaluate mathematical expressions directly in Prolog.
  • List Manipulation: Prolog frequently works with lists, and list operators (e.g., | and .) provide a convenient way to construct, destructure, and manipulate lists.
  • Logical Operations: Logical operators (comma , for AND and semicolon ; for OR) enable you to define complex logical conditions and conjunctions/disjunctions of goals and subgoals in Prolog rules.
  • Customization: Prolog allows you to define your own custom operators to match the terminology and requirements of your application. This customization can significantly improve code readability and domain-specific expressiveness.
  • Pattern Matching and Unification: Operators play a role in pattern matching and unification, a fundamental feature of Prolog. They help in matching structures within terms and variables, facilitating the search for solutions and drawing logical inferences.
  • Integration with External Systems: In some applications, Prolog may need to interact with external systems or languages. Custom operators can be defined to ease the integration process, making Prolog more versatile.
  • Compatibility with Existing Systems: Operators can be used to align Prolog code with existing systems, databases, or standards, allowing for smoother integration and data interchange.
  • Improved Rule Definitions: When defining rules in Prolog, operators can make the rules more intuitive and closely aligned with natural language, making it easier to encode domain-specific knowledge and expertise.

Syntax of Operators in Prolog Language

In Prolog, operators are defined using the :- op/3 predicate, where the syntax is as follows:

Here’s a breakdown of each component of the syntax:

  • Precedence: This is an integer value that represents the precedence or priority of the operator. Operators with higher precedence values are evaluated before operators with lower precedence values. Precedence values typically range from 1 (lowest precedence) to 1200 (highest precedence), but you can choose values within this range.
  • Type: This specifies the associativity and arity of the operator. It can have one of the following values:

xfx : Operator is infix and has the same precedence for both its left and right arguments.

xfy : Operator is infix, associates to the right (higher precedence for the right argument).

yfx : Operator is infix, associates to the left (higher precedence for the left argument).

fx : Operator is prefix and has higher precedence than any other operators.

fy : Operator is prefix and has the same precedence as xfx operators.

xf : Operator is postfix and has the same precedence as xfx operators.

yf : Operator is postfix and has the same precedence as xfx operators.

  • Operator: This is the actual operator symbol, which can be a sequence of characters or symbols. You define the custom operator here.

Here are some examples of defining operators in Prolog:

In the examples above:

  • likes is defined as an infix operator with a precedence of 500, so you can use it between two terms in expressions like alice likes chocolate .
  • and is defined as an infix right-associative operator with a precedence of 600, allowing expressions like X and Y and Z to associate to the right.
  • not is defined as a prefix operator with a precedence of 700, so you can use it as a unary operator like not P to negate the term P .

Features OF Operators in Prolog Language

Operators in Prolog provide several important features and capabilities that enhance the expressiveness and flexibility of the language. Here are the key features of operators in Prolog:

  • Customization: Prolog allows you to define custom operators tailored to your specific problem domain. This customization enables you to create domain-specific languages (DSLs) and express concepts and operations in a way that closely matches the terminology of your domain.
  • Improved Readability: Operators make Prolog code more readable by allowing you to use familiar symbols and notations to represent relationships, operations, and conditions. This can make the code more accessible to domain experts and non-programmers.
  • Conciseness: Operators enable you to express complex relationships and operations in a concise and natural way. This can lead to more compact and expressive Prolog code, reducing the need for verbose or cumbersome representations.
  • Mathematical Expressions: Prolog’s support for arithmetic operators allows you to work with mathematical expressions directly within Prolog programs. This is particularly useful for applications that involve numeric calculations and equations.
  • Logical Operators: Operators for logical operations (comma , for AND and semicolon ; for OR) make it easy to define complex logical conditions and combine multiple goals and subgoals in Prolog rules and queries.
  • Pattern Matching: Operators play a crucial role in pattern matching and unification, which are fundamental features of Prolog. They help in matching structures within terms and variables, facilitating the search for solutions and logical inference.
  • Precedence and Associativity: Operators can be defined with precedence and associativity rules, allowing you to control the order of evaluation in complex expressions. This ensures that expressions are evaluated according to the intended logic.
  • Integration with External Systems: Custom operators can be defined to ease the integration of Prolog with external systems or languages. This flexibility allows Prolog to interact effectively with other components of a larger system.
  • Domain-Specific Expressiveness: Operators are instrumental in creating DSLs within Prolog. By defining custom operators, you can build Prolog programs that are highly expressive and closely aligned with the concepts and operations of your specific domain.
  • Compatibility: Operators can be defined to align Prolog code with existing standards, practices, or external systems. This ensures compatibility and seamless integration with other parts of a project or ecosystem.
  • Improved Rule Definitions: Operators help in defining rules that closely resemble natural language expressions, making it easier to encode domain-specific knowledge and expertise in Prolog programs.

How does the Environment Setup works in Prolog language

Setting up the environment for Prolog involves installing a Prolog interpreter or system and configuring your development environment to work with Prolog programs. Here’s a general overview of how the environment setup works for Prolog:

  • Choose a Prolog Implementation: There are several Prolog implementations available, each with its own features and capabilities. Some popular Prolog implementations include SWI-Prolog, GNU Prolog (gprolog), and Sicstus Prolog. Choose the one that best suits your needs based on factors like platform compatibility and available libraries.
  • Installation: Install the chosen Prolog implementation on your computer. Installation steps may vary depending on your operating system (Windows, macOS, Linux) and the specific Prolog system you’re using. Typically, you can download an installer or package manager for your OS and follow the installation instructions.
  • Environment Variables (Optional): Some Prolog implementations may require you to set environment variables to specify the location of Prolog executable files or libraries. Check the documentation for your Prolog system to see if this is necessary and how to configure these variables.
  • Integrated Development Environment (IDE) (Optional): While you can write Prolog code using a plain text editor, using an IDE specifically designed for Prolog can greatly improve your development experience. Some Prolog IDEs come with features like code highlighting, debugging tools, and integration with version control systems. SWI-Prolog, for example, provides its own IDE called SWI-Prolog IDE (SWI-IDE).
  • Editor Configuration: If you’re not using a Prolog-specific IDE, configure your text editor or integrated development environment (IDE) to recognize Prolog code files (usually with a .pl or .pro extension). Configure syntax highlighting and indentation to make your code more readable.
  • Writing Prolog Programs: Use your chosen text editor or IDE to write Prolog programs. Prolog programs typically consist of facts, rules, and queries. Make sure to save your programs with the appropriate file extension.
  • Running Prolog Programs: You can run Prolog programs by launching the Prolog interpreter and loading your program file. This allows you to interactively query your program and receive responses. Alternatively, you can run Prolog programs directly from the command line or by executing a script.
  • Debugging (if needed): If your Prolog system provides debugging tools, learn how to use them effectively to identify and resolve issues in your code.
  • Documentation and Learning Resources: Familiarize yourself with the Prolog language by referring to the official documentation of your chosen Prolog implementation. Additionally, there are many Prolog tutorials, books, and online resources available to help you learn and master Prolog programming.
  • Advanced Configuration (Optional): Depending on your project’s requirements, you may need to configure additional settings or libraries for your Prolog environment. This could include integrating Prolog with external libraries, databases, or other programming languages.

Example OF Operators in Prolog Language

In Prolog, operators are often used to create custom operators that make your code more expressive and aligned with your problem domain. Here are some examples of custom operators in Prolog:

  • Mathematical Operators: You can define custom operators to represent mathematical operations. For example, let’s define a custom operator add for addition and subtract for subtraction:

With these operator definitions, you can write arithmetic expressions like this:

  • Domain-Specific Operators: Custom operators can be defined to create domain-specific languages (DSLs). Suppose you’re working on a scheduling application. You can define operators like before and after for defining time constraints:

Now, you can express temporal relationships like this:

  • Logical Operators: Custom logical operators can enhance the readability of your Prolog code. For example, you can define operators like and and or :

Then, you can use them in logical expressions:

  • Units of Measurement: If your Prolog application deals with units of measurement, you can define operators to represent these units. For instance, you can define operators for meters and seconds:

This allows you to work with units in your program:

  • Semantic Operators: In natural language processing applications, you can define operators to represent semantic relationships. For example, you can define operators like is_a and part_of :

Then, you can express relationships in semantic networks:

Applications of Operators in Prolog Language

Operators in Prolog have various applications in enhancing code readability, expressiveness, and usability in different problem domains. Here are some common applications of operators in Prolog:

  • Mathematical Expressions: Operators can be used to define custom operators for arithmetic operations, making it easier to write and read mathematical expressions within Prolog programs. For example, you can define custom operators for addition, subtraction, multiplication, and division.
  • Domain-Specific Languages (DSLs): Operators allow you to create domain-specific languages within Prolog, tailored to your specific application domain. This is particularly useful when working on specialized tasks like scheduling, constraint solving, or natural language processing. Custom operators can represent domain-specific concepts and operations more naturally.
  • Temporal and Spatial Reasoning: When dealing with time and spatial relationships, operators can be defined to represent “before,” “after,” “inside,” “outside,” and other spatial and temporal constraints. This is beneficial for applications like event scheduling, geographic information systems, and simulations.
  • Logical Reasoning: Custom operators for logical operations such as conjunction, disjunction, and implication can enhance the readability of logical rules and queries in Prolog. This is especially useful in rule-based systems, expert systems, and knowledge representation.
  • Units of Measurement: Operators can be employed to represent units of measurement, allowing you to work with quantities and units more naturally. This is valuable in scientific and engineering applications where units play a crucial role.
  • Semantic Networks: In natural language processing and semantic web applications, custom operators can be used to represent semantic relationships between concepts. Operators like “is_a,” “part_of,” and “related_to” can be defined to build semantic networks and ontologies.
  • Constraint Logic Programming: Custom operators are often used in constraint logic programming languages (e.g., CLP(R), CLP(Q)) to express complex constraints more intuitively. These languages leverage operators for real and rational arithmetic, among other constraints.
  • Pattern Matching: Operators can be applied to pattern matching and unification, allowing you to match specific patterns within terms more effectively. This is fundamental in Prolog’s search for solutions and logical inference.
  • Knowledge Representation: Operators play a significant role in representing knowledge and relationships in knowledge bases. Custom operators can help encode domain-specific knowledge more naturally and support efficient querying.
  • Natural Language Processing (NLP): In NLP applications, operators can represent linguistic relationships and grammatical structures. This aids in parsing and analyzing natural language text.
  • Code Generation: Operators can be used to generate code or queries dynamically based on specific criteria or user input. This is applicable in code generation tools and systems.
  • Legacy System Integration: When integrating Prolog with legacy systems or external data sources that use specific notations or symbols, custom operators can be defined to bridge the gap and enable seamless integration.

Advantages of Operators in Prolog Language

Operators in Prolog offer several advantages that enhance the language’s expressiveness, readability, and flexibility. Here are the key advantages of using operators in Prolog:

  • Improved Readability: Custom operators allow you to express relationships, operations, and conditions in a way that closely resembles natural language. This makes Prolog code more readable and understandable, especially for non-programmers and domain experts.
  • Expressiveness: Operators enable you to create code that is more expressive and concise. Complex relationships and operations can be represented with custom operators, reducing the need for verbose or convoluted code.
  • Domain-Specific Languages (DSLs): Operators empower you to create domain-specific languages within Prolog. This is particularly valuable when working on specialized tasks or problem domains, as it allows you to model and solve problems in a way that aligns with the domain’s terminology and concepts.
  • Natural Language Alignment: Custom operators can be designed to align with the natural language used in your domain. This improves communication between domain experts and developers, as code reflects the domain’s vocabulary and concepts more closely.
  • Mathematical Clarity: When working with mathematical expressions, operators provide a clear and intuitive way to represent arithmetic operations, making it easier to write and understand mathematical code.
  • Logical Clarity: Custom operators for logical operations (e.g., AND, OR) enhance the clarity of logical rules and queries. This is crucial in rule-based systems, expert systems, and knowledge representation.
  • Temporal and Spatial Relationships: Operators can be used to represent temporal and spatial relationships, making it easier to express constraints related to time and space. This is beneficial in applications like scheduling, simulation, and geographic information systems.
  • Units of Measurement: Custom operators for units of measurement enable you to work with quantities and units more naturally, which is advantageous in scientific and engineering applications.
  • Semantic Networks and Ontologies: In semantic web and natural language processing applications, operators help build semantic networks and ontologies by representing semantic relationships between concepts and entities.
  • Pattern Matching and Unification: Operators are integral to pattern matching and unification in Prolog, enabling efficient searching for solutions to queries and drawing logical inferences.
  • Customization: Prolog’s support for custom operators provides the flexibility to adapt the language to specific project requirements and coding conventions, making it more versatile.
  • Code Generation: Operators can be used for dynamic code generation, enabling the creation of code or queries based on specific criteria or user input. This is valuable in code generation tools and systems.
  • Integration with External Systems: Custom operators can facilitate the integration of Prolog with external systems or data sources that use specific notations or symbols, streamlining the data interchange process.
  • Legacy System Compatibility: When working with legacy systems that use unique notations, operators can be defined to bridge the gap between Prolog and these systems, ensuring compatibility and smooth integration.

Disadvantages of Operators in Prolog Language

While operators in Prolog offer several advantages, they also come with certain disadvantages and considerations. Here are the disadvantages and challenges associated with using operators in Prolog:

  • Potential Confusion: Custom operators, especially those with non-standard symbols or semantics, can potentially confuse readers who are not familiar with the specific domain or project. Code maintainability can be compromised if operators are overused or defined ambiguously.
  • Learning Curve: When working with code that heavily relies on custom operators, newcomers to the project or language may face a steep learning curve. Understanding the meaning and precedence of custom operators requires familiarity with the project’s conventions.
  • Portability Issues: Code that relies heavily on custom operators may not be easily portable to different Prolog systems or dialects. Different Prolog implementations may have varying levels of support for custom operators, and operator definitions may need to be adapted.
  • Readability Trade-offs: While custom operators can enhance expressiveness, excessive use of operators can lead to code that is less readable and harder to maintain. Striking the right balance between custom operators and more conventional Prolog constructs is important.
  • Semantic Ambiguity: Care must be taken when defining custom operators to ensure that their semantics are clear and unambiguous. Ambiguous operator definitions can lead to unexpected behavior or logical errors in code.
  • Compatibility with Libraries: Custom operators may not be compatible with Prolog libraries and external code that rely on standard Prolog syntax. This can limit the reuse of libraries and components.
  • Documentation and Learning: Projects that heavily utilize custom operators may require comprehensive documentation to explain the semantics and usage of these operators. Developers must invest time in learning the custom operator conventions.
  • Maintenance Challenges: As a project evolves, the meaning or usage of custom operators may change. This can introduce maintenance challenges, especially in large codebases where operators are widely used.
  • Collisions and Conflicts: Care must be taken to avoid naming conflicts or collisions between custom operators and built-in Prolog predicates or operators. Conflicts can lead to unexpected behavior or errors.
  • Debugging Complexity: Debugging code that uses custom operators can be more complex, as the meaning and behavior of these operators must be considered during the debugging process.
  • Semantic Precision: Custom operators may not always provide the same level of semantic precision as more conventional Prolog constructs. Careful design and documentation are necessary to ensure that custom operators behave as intended.
  • Overhead in Operator Definitions: Defining custom operators adds a layer of complexity to the code, especially if there are many operators with varying precedences and types. This can make the code harder to understand and maintain.

Future development and Enhancement of Operators in Prolog Language

The future development and enhancement of operators in the Prolog language can contribute to making the language more powerful, expressive, and user-friendly. While Prolog has a well-established foundation for defining operators, there are several areas where improvements and enhancements can be considered:

  • Standardization: Encourage standardization of operator definitions across Prolog implementations. A common set of operators and operator precedence levels could help improve code portability between different Prolog systems.
  • Operator Libraries: Develop and maintain libraries of commonly used custom operators for specific problem domains. These libraries can provide reusable and well-documented operators for various applications, reducing the need for users to define their own operators from scratch.
  • Operator Alias: Introduce support for operator aliases or synonyms. This feature would allow multiple operator symbols to represent the same operator, enhancing code readability and compatibility with different coding styles.
  • Tooling Support: Enhance Prolog development environments and integrated development environments (IDEs) with features like auto-completion, syntax highlighting, and code analysis specifically tailored to operator usage. This can help developers work with operators more effectively.
  • Semantic Annotations: Develop a mechanism for annotating custom operators with semantic information. This could provide a standardized way to document the intended semantics and usage of custom operators, improving code clarity and understandability.
  • Operator Validation: Implement validation and linting tools that can check the correctness of operator definitions and detect potential ambiguities or conflicts in code.
  • Operator Documentation: Promote best practices for documenting operator conventions and usage within Prolog code. Encourage developers to provide clear and comprehensive documentation for custom operators.
  • Operator Scoping: Explore mechanisms for scoping operators within modules or namespaces to prevent unintended operator conflicts in large codebases.
  • Operator Overloading: Consider adding support for operator overloading, allowing the same operator symbol to have different meanings in different contexts or data types. This can make Prolog more versatile for object-oriented or data-driven programming.
  • User-Friendly Error Messages: Improve error messages related to operator definitions, making them more informative and helping developers quickly identify and resolve operator-related issues.
  • Interactive Operator Editing: Implement features in Prolog development environments that simplify the creation and modification of operators interactively, reducing the barrier to defining custom operators.
  • Community Involvement: Encourage active participation from the Prolog community in shaping the future of operators. Seek input from users and domain experts to identify common operator needs and challenges.
  • Cross-Dialect Compatibility: Promote compatibility between different Prolog dialects regarding operator definitions and usage to facilitate code sharing and collaboration.
  • Academic Research: Support academic research in the field of Prolog and operators, which can lead to innovative approaches and best practices for operator design and usage.
  • Integration with Other Languages: Explore ways to enhance the integration of Prolog with other programming languages, allowing for seamless use of Prolog operators in multi-language applications.

Equivalent Technical Articles

Control Statement in C

Conditional Statements in C Programming

Do-While Loop

Do-While Loop In C Programming

while loop in C

While Loop in C Programming Language

Javatpoint Logo

Computer Graphics

Computer Network

  • Interview Q

Prolog Tutorial

Clauses & predicates, satisfying goals, operations & arithmetic, input & output, preventing backtracking, prolog examples.

JavaTpoint

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • Sources/building
  • Docker images

External

  • Command line
  • Prolog syntax
  • HTML generation
  • Publications
  • Rev 7 Extensions
  • Getting started
  • Development tools
  • RDF namespaces
  • GUI options
  • Linux packages
  • Report a bug
  • Submit a patch
  • Submit an add-on
  • External links
  • Contributing
  • Code of Conduct
  • Contributors
  • SWI-Prolog items
  • View changes
  • Introduction
  • Initialising and Managing a Prolog Project
  • Built-in Predicates
  • SWI-Prolog extensions
  • Tabled execution (SLG resolution)
  • Constraint Logic Programming
  • CHR: Constraint Handling Rules
  • Multithreaded applications
  • Coroutining using Prolog engines
  • Foreign Language Interface
  • Using SWI-Prolog in your browser (WASM)
  • Deploying applications
  • Packs: community add-ons
  • The SWI-Prolog library
  • Hackers corner
  • Compatibility with other Prolog dialects
  • Glossary of Terms
  • SWI-Prolog License Conditions and Tools
  • Bibliography

D Glossary of Terms

Expressed as “X is a parent if X is a father of someone” . See also variable and predicate .

In Prolog, the expression a+b is exactly the same as the canonical term +(a,b) .

Unlike assignment (which does not exist in Prolog), unification is not directed.

See also unify .

  • doc-needs-help

Picture of user Andy Green.

Some corrections

"A Prolog variable is a value that‘is not yet bound'."

That sound not correct (it would explain why var/1 is called var/1 and not unbound/1 though, but is in contradiction with all other usage of the word 'variable', in particular with the usage under "binding of a variable").

Better: A "variable" is a name (with clause scope) denoting a term or an empty cell. If it designates an empty cell, it is an unbound or uninstantiated variable, otherwise it is a bound variable, namely a variable bound to the term it denotes. The "binding state" of a variable may change from unbound to bound. Trivially:

which should really have been written

OTOH, there is a slight shift in the meaning of the word "variable" when used for a variable name in the head (where it is always unbound as it appears in unification) and in a goal (where its "bounded-ness/instantiated-ness status" changes from "fresh & unbound" to "still unbound" to "bound/partially bond" to "bound/ground").

In all these case, X is a "variable", but the meaning changes.

It is actually clearer to say that X is a variable name and denotes en empty cell ("X is an unbound variable") or a (proper? nonempty?) term. (apparently an empty cell is also a "term")

Some possible additions

Some adapted from

  • "Deduction Systems", Rolf Socher-Ambrosius, Patricia Johann, Springer 1997
  • "Memoing for Logic Programs", David S. Warrne, CACM Marc 1992 (Vol.35 No.3)
  • Deduction/Induction/Abduction from "Abductive reasoning in Prolog and CHR" (Henning Christiansen, 2005)
  • "typein module" as used on the page operators : the module into which code typed in at the toplevel (using the [user] prompt) is added (I suppose).

Det, Semidet and Nondet

See here: https://eu.swi-prolog.org/pldoc/man?section=preddesc

Computation

  • Comma-list (as used on the page for tabling): A list constructed with functor `,/2`, which is not a real list as it terminates in a list element: (1,2,3) = (1,(2,3)) . Generally used as a conjunction.
  • Character or Char is an atom of length 1. Prolog has no specific character type.
  • Predicate Activation or just Activation : Basically, the stack frame of the predicate call. The runtime context of a clause in which variables denote concrete values (terms or empty cells). Corresponds to a "Byrd Box".
  • Unbound variable vs. Unbound value : An unbound variable is a variable name that denotes an "empty cell" in memory. It is a variable name for which var/1 exactly succeeds at call time (but maybe not later, after a unification occurs. On the other hand, definitely earlier because you cannot "unbind" a variable except through backtracking; this is waht i means for Prolog to be "assign-once"). An unbound value is a position in a complex term that denotes an "empty cell" in memory but that does not have a name. For example: length(L,2) . L is an unbound variable at first that is then unified with a complex term (a list of length 2) with 2 unbound values, which, when printed, appear as 2 unbound variables (i.e. their arbitrarilly chosen names are printed rather than their nonexistent content): L = [_5038, _5044] .)
  • Predicate well-behavedness
  • Predicate steadfastness . A more general definition: In "The Craft of Prolog" Richard O’Keef writes on page 96 that "we call the property of refusing to give wrong answers even when the query has an unexpected form (typically supplying values for what we normally think of as inputs*) steadfastness". Note that the ISO standard says nothing about this concept, although built-in predicates are generally "steadfast".
  • Partial term / Partially ground term : That term that is an unbound variable or may contain unbound variables not 100%% sure whether an unbound variable actually counts as such; the mode indicator descriptions seem to imply no).
  • Floundering : When negation-as-failure pretzels itself and leads to wrong answers because the negated goal contains unbound variables (i.e. is nonground). Raymond Reiter writes in "Knowledge in Action" (MIT Press, 2001): "Eclipse Prolog provides two negation operators, one of which suspends itself on negative, non-ground atoms, hoping that their free variables will eventually become bound during the rest of the computation, at which point the operator resumes."
  • call(atom_concat,prefix,suffix,R) .
  • call(atom_concat(prefix),suffix,R) .
  • call(atom_concat(prefix,suffix),R) .
  • call(atom_concat(prefix,suffix,R)) .
  • Fresh variable - a Prolog variable name that has not been used "to the left" and denotes a newly allocated "empty cell" in memory. For example, _ is always fresh where it appears.
  • Iterative Deepening - a heuristic to expand search trees which can be used in particular to transform Prolog's depth-first search strategy into a depth-limited breadth-first search strategy. This expands shallow nodes first and avoids accidental infinite descent on depth-first search. See "Depth-First Iterative Deepening: An Optimal Admissible Tree Search" by Richard Korf, Artificial Intelligence 27 (1985), Elsevier. Also Wikipedia . See also call_with_depth_limit/3 and call_with_inference_limit/3
  • Guard - a test made at the beginning of a clause body for conditions that cannot be captured by simple head unification. Often followed by a cut to "commit" to the clause. Generally done using `,/2` but sometimes using ->/2 . Example:
  • Guarded Horn Clauses , Guarded Definite Clauses particular logic programming languages derived from Prolog meant to be run on (highly) parallel machines (in particular so-called "5th generation" hardware). This research branch seems to have been abandoned (for now). Languages like PARLOG and Parallel Prolog are ancestors. See also: The deevolution of concurrent logic programming languages .
  • CHR - Abbreviation for Constraint Handling Rules , an approach promoting forward-chaining rules working on a blackboard store. SWI-Prolog has an implementation running in the context of a single clause: CHR . See also: Wikipedia: Constraint Handling Rules
  • Clause indexing - how a Prolog implementation looks up a matching clause head. Indexing may or may not be done on several arguments. SWI-Prolog indexes on first argument only, so if you want high discrimination by cases, move the most discriminatory parameter to the first place.
  • Clean/Defaulty representation - a question of coding style. Clean representations can be efficiently distinguished by head unification alone. Defaulty (a pun on "faulty") representations force a coding style where a clause head matches, and the body distinguishes. This may be inefficient at runtime. See Triska's Triska's discussion at Clean vs. defaulty representations .
  • Cell A memory location. It is either empty or holds an atomic term or a compound term which referencing other cell containing the compound term name and the compound term arguments. A special case is the list cell with name `[|]` and two arguments (i.e. with arity 2). In LISP, this is called the "consbox", with the first argument the "car" and the second the "cdr". Once a cell has been filled, it becomes indistinguishable from other cells with the same content ( my_atom == my_atom ) or at the root of graphs of cells forming ground terms ( f(g(a,b),c) == f(g(a,b),c) ). This allows the underlying machinery to share parts of graphs representing terms. In a Prolog program, a cell, or rather, the root of graph of cells is denoted by a variable ( X = f(g(a,b),c) ). Thinking in terms of cells instead of terms is generally not needed unless empty cells and non-logical usage thereof enters the picture.
  • List cell a cell holding the compound term `[|]` (in SWI-Prolog, traditionally `.` in other Prologs) and two arguments. In a well-constructed list the, there is a list element on argument position 1 and there is a next listcell of the list backbone or [] on element position 2.
  • Empty cell a cell holding (as yet) nothing but which may be set to an atomic value of the root of a graph of cells as computation progresses. Setting an empty cell can be done only once (Prolog is "assign-once") but can be rolled back on backtracking. Empty cells are denoted by initially fresh variables in a Prolog clause. Non-atomic terms, which are roots of trees and sometimes graphs of cells, can have empty cells at their leaves nodes. Unlike ground terms, empty cells are distinguishable and have identity: X \== Y. : what these fresh variables denote, which are empty cells, are not the same, but X=a,Y=a,X==Y. . Empty cells are merged via unification: X \==Y, X=Y, X == Y : X and Y now designate the same empty cell. Thinking in terms of empty cells is not logical but computational and stateful in nature, and is done in the parts of the Prolog program which are doing state manipulation, for example those dealing with difference lists of open lists.
  • freeze/2 and family: freeze(X,write("Hello")),X=1. prints Hello .
  • dif/2 (ensure two variables are always different) and family: dif(X,Y),X=1,Y=2. succeeds but dif(X,Y),X=1,Y=1. fails
  • Attributed variables : A generalization which allows the programmer to set/get arbitrary attributes on an empty cell and perform arbitrary decisions on unifications.
  • Linting : The process of checking Prolog code for style errors and dubious constructions prior to compilation. This is done by library(check) and library(codewalk) . See also library(prolog_xref) See also the Wikipedia entry on the lint program
  • Pure Prolog : Unclear, depends on opinion. A Prolog that only allows Horn clauses, without control-flow constructs like !, ->, no negation-as-failure \+ (but presumably still allows \= as the FOL "not equal"), possibly no meta-predicates incl. "call", which may possibly terminate independently of clause ordering. A Prolof which is "nearer" an ideal fragment of First-Order Logic.
  • Proper Prolog : A proper Prolog interpreter is one that evaluates a negative literal not A, using negation-as-failure, and moreover, does so only when (at the time of evaluation) the atom A is ground. When A is not ground, the interpreter may suspend its evaluation, working on other literals until (with luck) A does become ground, or it may abort its computation. Either way, it never tries to fail on non-ground atoms. (Directly copied from Raymond Reiter: "Knowledge in Action", MIT Press, 2001 p. 107)

Classes of logic programs

  • Definite logic program or Positive logic program or Horn logic program : A logic program consisting of clauses of the form `a_0 :- a_1, .... , a_m (i.e. Prolog programs without negation)
  • Normal logic program or General logic program : A logic program consisting of clauses of the form `a_0 :- a_1, .... , a_m, \+ a_{m+1}, ... \+ a_n.`, where \+ stands for negation-as-failure. (i.e. Prolog program with negation)
  • Extended logic program : A logic program consisting of clauses of the form `l0 :- l_1, .... , l_m, \+ l_{m+1}, ... \+ l_n.`, where l0 ... ln denote literals formed by means of strong negation l = a or l = ¬a. ( Not supported in Prolog)
  • Positive disjunctive logic program : A logic program consisting of non-Horn clauses of the form `a_0 ⋁ ... ⋁ a_n :- b1_1, .... , b_m (i.e. disjunctions are allowed in the head, making formulation of "uncertain knowledge" feasible; not supported in Prolog)
  • Deduction , reasoning within the knowledge we already have, i.e. from those facts we know and those rules and regularities of the world that we are familiar with. E.g. reasoning from causes to effects: _"If you make a fire here, you will burn down the house."_ (Henning). To a first approximation, Prolog performs reverse deduction, aka. goal-directed search: _"To burn down the house, make a fire here"_, but in relatively basic and "programming" context. To apply this to actual planning and commonsense reasoning you need to have a more extensive logical infrastructure than Prolog provides out of the box. See for example Event Calculus .
  • Induction , finding general rules from the regularities that we have experienced in the facts that we know: these rules can be used later for prediction: _"Every time I made a fire in my living room, the house burnt down, aha, ... the next time I make a fire in my living room, the house will burn down, too."- (Henning) This is the purview of (unsupervised and symbol-based) machine learning. See Inductive Logic Programming for on introduction on how logic programming can be used in this domain.
  • Abduction , reasoning from observed results to the basic fact from which they follow, quite often it means from an observed effect to produce a qualified guess for a possible cause: _"The house burnt down, perhaps my cousin has made a fire in the living room again."_ The corresponding formalization and extension for logic programming is the subject of Abductive Logic Programming
  • Deductive database : Database implemented through a logic program that allows no function symbols and thus is based on a finite universe. Datalog is the paradigm here. (For a deductive database connected to a LISP-like language: datomic ). (How does this compare to a relational database with recursive operations / fixpoint operations? Should be the same...)
  • Extensional database (EDB) : The part of a logic program (or deductive database) that consist in facts.
  • Intensional database (IDB) : The part of a logic program (or deductive database) that consists in rules (implications and integrity constraints). In a deductive database, EDB+IDB form a compressed representation of all the ground atoms that can be deduced going bottom-up chaining implications "forward" from premiss to conclusion to conclusion until a fixpoint of the ground atoms has been reached. When doing a proof "top-down", one is verifying whether an atom is indeed a member of that fixpoint.
  • Herbrand Universe : The set of all ground terms constructed from constants and function symbols that appear in the program.
  • Herbrand Base : The set of all ground atoms ("atoms" in the logical sense, i.e. predicate calls, not in the Prolog sense of "distinguishable identifiers/strings") that can be constructed from predicate symbols that appear in the program and terms from the Herbrand Universe.
  • Proof witness or proof solution : a set of ground or partially ground terms that form a solution to a query with unbound variables: length([1,2],L) , gives L=2 ; the 2 is the proof witness (the proof is "constructive" and doesn't just say true or false). Sometimes Prolog emits a "template proof witness" instead: length(List,2) gives List=[_,_] , which is really a (most general) template for lists of length 2.
  • Free variable - this is sometimes used in the sense of a variable that is unbound (in the Prolog sense: it has no value). That's confusing though. In logic, the "free variable" in a formula is one which is not bound (in the logic sense) by a quantifier (or a lambda if those are allowed). A bound variable is said to be "in the scope of a quantifier". The same variable (variable name) can occur in a formula in places where it is bound and free, so we have to really talk about free and bound occurrences of variables rather than free and bound variables.
  • Theory - A set of true sentences (expressed in and part of some specified logic). Concretely, a Prolog program is a theory with facts and sentences pre-labeled as "true".
  • Model Theory : In mathematics, model theory is the study of the relationship between formal theories (a collection of sentences in a formal language expressing statements about a mathematical structure), and their models, taken as interpretations that satisfy the sentences of that theory.
  • Proof Theory : Proof theory is a major branch of mathematical logic that represents proofs as formal mathematical objects, facilitating their analysis by mathematical techniques. Proofs are typically presented as inductively-defined data structures such as plain lists, boxed lists, or trees, which are constructed according to the axioms and rules of inference of the logical system. As such, proof theory is syntactic in nature, in contrast to model theory, which is semantic in nature.
  • Model - A truth value assignment to atoms (i.e. facts) that makes all of the sentences of a theory true (and doesn't imply inconsistencies).
  • Valid : : If the sentence is true in all models.
  • Satisfiable : If there is at least one model in which the sentence is true.
  • Unsatisfiable : If there is no model in which the sentence is true.
  • Statement - "A sentence put to work" . From Wikipedia: Statement : (a) a meaningful declarative sentence that is true or false, or (b) the assertion that is made by a true or false declarative sentence. In some treatments "statement" is introduced in order to distinguish a sentence from its informational content. A statement is regarded as the information content of an information-bearing sentence. Thus, a sentence is related to the statement it bears like a numeral to the number it refers to. Statements are abstract logical entities, while sentences are grammatical entities.
  • Expression - From Wikipedia: Expression : In mathematics, an expression or mathematical expression is a finite combination of symbols that is well-formed according to rules that depend on the context.
  • Proposition - More or less the same as a Statement or a Sentence. See Wikipedia: Proposition . In propositional logic , we do not work at level of expressions involving relations and objects and equality and quantifiers but at the level of (opaque) propositional variables linked by logic operators; the propositional variables takes one a value from some finite set (generally a value of the finite set {true,false}; but one can generalize to non-logic settings, for example in belief networks the propositional variable can take on any of a set of values describing an outcome and logical connectives take on the meaning of set operations)
  • Theorem - A sentence (of some logic adjoined to some theory) that can be labeled true ("proven") by a proof procedure. Goals for which the Prolog prover succeeds (which the Prolog prover accepts) are theorems for the pair (Prolog logic,Prolog program). A theorem is of course accompanied by at least one proof. Note that most Theorems are of low interest: for example, in the theory of Peano Numbers, 1+2<4 . See also: Wikipedia: Theorem , which has a glossary of related terms (Corollary etc.). That page also cites Paul Hoffman as _"It has been estimated that over a quarter of a million theorems are proved every year."_ Well, with Prolog you can prove a million theorems in a minute!
  • Tautology - A sentence (of some logic adjoined to some theory) that is true in all models. For example, in classical propositional logic: `(A ⇒ B) ⇔ (¬A ∨ B)` See also: Wikipedia: Tautology .
  • Signature of a logic, Sigma = `<F,P>`, is a set of function symbols name/arity adjoined to a set of predicate symbols name/arity
  • Atom (logic) (not to be confused with the "atom" of Prolog), or "atomic formula" is a word p(t1,...,tn) , n>=1 where p is a predicate symbol from a set P and the ti are terms from `T(F,V)`, build from a set of function symbols F and variable symbols from set of variable symbols V . The atom can also be a word of the form s = t where s , t `T(F,V)`. The set of atoms may be written `A(F,P)` (note that 0-arity predicate symbols are in principle not allowed)
  • Literal either an atom (a "positive literal") or its negation (a "negative literal") appearing in a formula. In Prolog, there is some subtlety involved with the fact that the negation is "weak" in the sense that it expresses negation-as-failure (absence of positive knowledge) instead of "strong" (presence of negative knowledge, as expressed by the negation of negation in classical (or other) logic). Although many approaches have been proposed to extend Prolog with strong negation, none of those has seen general acceptance so far. Instead, strong negation can be found in a different approach to logic programming: Answer Set Programming . The symbols for negation can be ~ or ¬ or naf or \+ . It depends on the author but generally ¬ is the strong negation.
  • Formula of a logic is the set of words inductively built from "atomic formula" using logical connectives (not, and, or, implies, iff, maybe less, maybe more) and the two quantifiers (adjoined to a variable) "there is" and "for all" (and maybe others). The set of formula `L(F,P)` over signature Sigma = `<F,P>` is said to be a first-order language over the signature Sigma. (See also Wikipedia: Well-Formed Formula ). An "open formula" is one with free variables, i.e. variables not bound by quantifiers. What the meaning, if any, of such an open formula is is context-dependent.
  • Clause - a general normal form for expressing predicate calculus formulas. It is a disjunction of literals (P1 ∨ P2 ∨ ....) whose arguments are terms. The terms are usually introduced by eliminating existential quantifiers. (from CACM March 1992)
  • Horn Clause - a clause containing (at most) one positive literal: H ∨ ~B1 ∨ ... (if Prolog is interpreted in the context of classical logic, the ~ is the strong negation). The term Definite Clause is used to denote a clause with exactly one positive literal. Prolog programs can be viewed as a set of definite clauses in which the positive literal is the head of the rule and the negative literals constitute the body or tail of the rule. (from CACM March 1992). A Horn Clause without negative literals is called a fact H , otherwise a rule . Note that a clause without the positive literal can be interpreted as a logical constraint (not to be confused with constraint logic programming). These are not supported by Prolog (but are supported by ASP systems).
  • Horn Clause (alternative) (alternative, from a text by David Warren): A Horn clause in a first-order logic is a universally quantified implication in which conjunction of atomic formulas implies an atomic formula. The Horn clause in `∀X∀Y∀Z ( arc(X,Y) ∧ path(Y,Z) ⇒ path(X,Z) )` could be a part of a description of paths through a graph. (This definition has the advantage that it justifies calling A :- B,C,D a Horn clause in a logic that does not allow the equivalence A⇒B = ¬A∨B, which is intuitionistic (positive) logic, which is the logic that really applies to Prolog even though it is often said that we are dealing in classical logic).
  • Intuitionistic Logic An ensemble of logics (and more widely, a philosophical stance) which does not accept the premise of classical logic that every sentences be necessarily labeled exactly one of "true" or "false", but accepts that some statements may remain "not labeled" until a (human) decision has been taken about how to proceed. In effect, what Prolog does is label sentences true if it can -- and otherwise fail, leaving the question open. It thus actually works in a fragment of positive intuitionistic logic rather than classical logic. Which makes complete sense from a programming perspective. Note that in particular, the implication A⇒B is NOT equal to ¬A∨B in Intuitionistic Logic. Instead it is taken to be statement like "Given a proof of A, you are then allowed to state that you also have a proof of B". See also: Uniform Proofs as a Foundation of Logic Programming (Dale Miller et al. 1991) and the Introduction of Logic programming with strong negation and inexact predicates (Gerd Wagner, 1991) . More on the philosophy at the Stanford Encyclopedia of Philosophy: Intuitionsitic Logic and Constructive Mathematics . Also, the problem of the Continuum Hypotheses .

Proof machinery

  • Resolution (see Robinson 1965: "A Machine Oriented Logic Based on the Resolution Principle", which can be found on the Interwebs for free): A single inference step used to prove the validity of predicate calculus for­mulas expressed as clauses. In its simplest version: (P∨Q) ∧ (P∨R) ⊢ (Q∨R) which is called the resolvant. (from CACM March 1992). See also: Wikipedia entry
  • Linear Resolution
  • SL-Resolution (sometimes SL Refutation ) described in Linear resolution with selection function PDF) (Kowalski and Kuehner, 1971) stands for "Linear Resolution with Selection function" (probably backronymed) is an original automated theorem proving proof idea whereby Robinson resolution is applied to a single literal in each step: _Linear resolution with selection function is a restricted form of linear resolution. The main restriction is effected by a selection function which chooses from each clause a single literal to be resolved upon in that clause. This and other restrictions are adapted to linear resolution from Loveland's model elimination._ (adapted from Shanahan)
  • SLD-Resolution (sometimes SLD Refutation ) described in Predicate Logic as Programming Language (Kowalski 1974) it stands for "SL-Resolution for Definite clauses" and is SL-Resolution applied to Horn clauses. SLD-Resolution is still non-deterministic and needs to be further restricted to be implementable. Prolog is the result of applying a restricted form of SLD-Resolution to the definite clause subset of predicate calculus, as described by Colmerauer, Kanoui, Roussel, Pasero in "Un Système de Communication Homme-Machine", 1973 (Research Report, Université Aix-Marseille Luminy): The leftmost atom in a goal clause is always chosen to resolve against, definite clauses are tried top-to-bottom order and a depth-first search is employed, for efficiency reasosn, the unification algorithm omits the occurs check. In fact, SLD-resolution is not strictly speaking a form of SL resolution, since it is more liberal in the selection functions it allows. (text adapted from "Solving the Frame Problem" by Murray Shanahan, MIT Press, 1997).

"SLD resolution can be understood procedurally as executing a nondeterministic program with procedure calls" (David Warren),

  • SLDNF-Resolution (sometimes SLDNF Refutation ): SLD Resolution with "Negation as Failure" to implement a "weak negation" operator.
  • SLG-Resolution A proof strategy whereby intermediate results are cached ( tabled , this is called tabling and sometimes memoing ). This makes it possible to write programs without having to pay special attention to infinite descent during depth-first search if the clauses are badly ordered. Prolog behaves more like a bottom-up theorem prover. (This may have been called "OLD Resolution with Tabulation" OLD Resolution with Tabulation, Taisuke Sato, July 1986 alias "OLDT Resolution" in the 80s, not sure). See: tabling . Certainly a feature that all modern Prolog systems should have and that should be taught. Refutation completeness A property of the SLD proof method in that SLD is "refutation complete" for Horn clauses. This means that if a ground answer is a logical consequence of a program then there is an SLD refutation that generates/accepts that answer (or a more general one). There may, however be some proofs paths that are infinite in length. Since Prolog must search this tree for the answers, its depth-first search may get caught on an infinite path, before it gets to the answer.

The evolution of the Prolog proof approach

From the above, we have:

  • Resolution (Robinson 1965) (basic principle used in systems like "Markgraf Karl Refutation Procedure" of mid-70s .. mid 80s, with additional control heuristic to direct the search). Also in Hewitt's PLANNER language (not sure whether implemented, there are obviously efforts at retconning precedence & history here; in the end it doesn't matter ... next problem!).
  • ⇒ Linear Resolution (?)
  • ⇒ SL Resolution (Kowalski & Kuehner 1971). Kowalski is cited as: "I can recall trying to convince Hewitt that Planner was similar to SL-resolution."
  • ⇒ SLD Resolution (Kowalski 1974)
  • ⇒ PROLOG using (a modification of) SLD-Resolution (Colmerauer et al. 1973)
  • ⇒ PROLOG using SLDNF (many other branches exist)
  • ⇒ PROLOG using SLDNF and SLG

Completely different approaches at building proof systems exist: Those based on Sequent Calculus, bottom-up provers, Tableaux-based, Answer Set Programming (Stable Models) and probably others.

Furthermore

  • Stack Overflow: Fact, Rule, Procedure, Predicate
  • Glossary of Logic terms (PDF) by Marc Cohen

The parts of a list

  • A proper list or a **closed list* is a list that has the empty list [] as the terminating element of the list backbone ("list backbone" is not commonly used except by myself, but it's are pretty evocative, so I will use it here)

Example of a proper list: an empty list Empty and a list of length 3 List1 and of length 2 List2 .

The list Empty could also appear simply like this. There is no way to find out which of the above and the below is "really" the case from Prolog:

  • The backbone is formed by a series of list cells which are compound terms with name `[|]` and arity 2. In Prologs other than SWI-Prolog, the compound name is traditionally `.` -- but `.` is used for SWI-Prolog dicts now. A backbone can only be traversed from the "tip" to "fin". There is no way to fin a "prior list cell".
  • A variable List1 holding a list can be though of a referencing a "the first list cell" of the backbone. The predicate is_list/1 can be used to verify that the term reachable from List1 is indeed a proper list.
  • A variable List2 referencing a list cell further along the backbone sees a shorter list. Nevertheless, the data structure is shared between List1 and List2 and this fact is often exploited for (example, if an element reachable from both List1 and List2 is further instantiated, from X to 2 for example, then predicates holding either of List1 or List2 will see this change). See also: duplicate_term/2 and copy_term/2 .
  • An element of a list is any term (atomic or compound) that can be found at argument position 1 of a list cell.
  • The empty list is a distinguished list of length 0. In SWI-Prolog it is represented by a dedicated atomic term which is not an atom (other Prologs may have subtly differing representations)
  • The Head is a sequence of n>= 1 elements, most often just 1 element.
  • The Tail is a variable denoting the rest of the list (of length >=0) after the Head. The Tail can unifiy with [] .
  • [H|T]=[1,2,3]
  • [H1,H2|T]=[1,2,3]
  • [H1,H2,H3|T]=[1,2,3] ( T will not be [] - the list without the first three positions is the empty list)
  • [H1,H2,H3,H4|T]=[1,2,3] will fail.
  • The Tip of a list is the first list cell of the backbone (if it exists) or the empty list in case of an empty list (a bit synonymous with start of a list, beginning of a list, front of a list)
  • The Fin of a list is whatever is found on argument position 2 of the last list cell (if it exists). In a proper list, this is always the empty list.
  • Now we can talk about directions "tipwards" and "finwards"
  • A Prefix of a list is a sublist appearing at the start of a list, encompassing 0 <= n <= length list cells. It may be the empty prefix, which is [] . The empty list has an empty prefix.
  • A Suffix of a list is a sublist appearing at the end of a list any term (atomic or compound) that can be found at argument position 2 of a list cell (alternatively, or can appear as a Tail in destructuring). The last list cell (alternatively, a list of length 1) has an empty suffix. The empty list has no suffix (it is the suffix).
  • Prefix=[], Suffix=[], append(Prefix,Suffix,[]).
  • Prefix=[], Suffix=[1,2,3], append(Prefix,Suffix,[1,2,3]).
  • [H|T]=[1,2,3], Prefix=[H],Suffix=T, append(Prefix,Suffix,[1,2,3]).
  • [H1,H2|T]=[1,2,3], Prefix=[H1,H2],Suffix=T, append(Prefix,Suffix,[1,2,3]).
  • [H1,H2,H3|T]=[1,2,3], Prefix=[H1,H2,H3],Suffix=T, append(Prefix,Suffix,[1,2,3]).
  • prepend/add prefix/head : Newlist = [X|OldList] . If the list is seen as a stack, this is push . This is efficient.
  • append/add suffix/tail : append(OldList,Tail,NewList) . This is extremely expensive as it involves copying OldList . Practically never done. To borrow Perl terminology, this is shift (although Perl "shifts" at fin).
  • remove a head/prefix, remove at tip . OldList = [X|NewList] If the list is seen as a stack, this is pop . This is efficient.
  • remove a tail/suffix, removing at fin : append(NewList,Tail,OldList) . This is extremely expensive as it involves copying OldList into NewList . Practically never done. To borrow Perl terminology, this is unshift (although Perl "unshifts" at tip).

Special case: The open list*

An open list can still grow its backbone (it can be "further instantiated") because its Fin is not set: it is "empty cell". If the there is a variable naming the Fin, say Fin , then Fin is an unbound variable, var(Fin) returns true.

An open list is transformed into a closed list by unifying that Fin with [] .

A special case is the "empty open list", which is really just any unbound variable. (The future history of an unbound variable is always open, it could become anything, even the tip of a proper list).

Example of a nonempty open list:

An open list is simply created by: OpenList = [1,2,3|Fin]. . After Fin=[] it is then a proper list.

Difference Lists

A *difference list" (which is actually confusing terminology) is really just a "list difference": two variables which refer to two positions in a list: X=[a,b,c,d], X=[a,b|Y]. From there, you can infer the "list difference", which is the X list minus the Y list: [a,b,c] (and which in extremis can be generated with append(LDiff,Y,X). )

These two references can be packed into a term to pass them to other predicates: p(X-Y). p(X/Y). But they should not (why waste cycles?). Just use p(X,Y).

The above construction is useful when the underlying list is an "open list", where Y points to the empty cell "fin" (the write position) where new elements are appended by a producer, and X is trailing behind (the read position) where elements are consumed by a consumer. The "list difference" then is the current buffer, which is empty if X==Y, var(X), var(Y) and EOF is expressed by Y=[] .

Here is another representation of the above:

When based on an open list, when the empty cell at the "backbone fin" is called Fin and takes the role of Y above and the 'X' is called 'Tip':

Tip=[a,b,c,d|Fin]

We can obtain an element V at the tip: Tip=[V|NewTip] and use NewTip as new Tip in the next activation:

Analogous to imperative programming with pointers, Fin=[d|NewFin] grows the open list with d , and yields a fresh variable NewFin denoting the new fin, which is an empty cell.

This can continue for some time. Mayn algorithms do not consume at the tip but just append at the fin. In any case, when we are done: Fin=[] , which closes the list. Once that unification has been performed, a proper list can be found at Tip :

or if Tip and Fin were equal when the unification is performed, in which case the "list difference" is the empty list:

The "empty open difference list" is evidently trivially an empty cell (or two unbound variables denoting the same empty cell): Tip=Fin . It's a bit borderline. Is this really a "list"?

What do we call what a predicate call does?

It can fail or succeed of course (or throw an exception, rudely moving us back from logic-land back into programming-land), but if it succeeds:

  • length([a,b,c],3) verifies/checks the length of list [a,b,c]
  • length([a,b,c],3) verifies/checks whether list [a,b,c] is a member of the preimage of 3 (technically of the set {3}).
  • This is often called "going forward"
  • length([a,b,c],L) computes/deduces L from [a,b,c] or maps [a,b,c] to L
  • append([a,b],[c,d],X) . X contains no information about the "input"
  • append_reversible([a,b],[c,d],[X,PrefixLen]) . [X,PrefixLen] contains enough information to "get back" to the input!
  • Hallucinate information (this is a bad idea): length(L,3) yielding [a,b,c] ? NOPE!
  • Propose a most generic template containing unbound values that unifies with any member of the preimage: length(L,3) yielding [_,_,_] . Yes!
  • Generate the members of the pre-image if they can be enumerated: member(X,[a,b,c]) yields a , b , c in turn.
  • If the pre-image is higher-dimensional, this can become complex: append(L1,L2,[a,b,c]). yields L1 = [],L2 = [a, b, c] ; L1 = [a],L2 = [b, c] ; L1 = [a, b],L2 = [c] ; L1 = [a, b, c],L2 = []

IMAGES

  1. Prolog Assigment for university

    assignment operator in prolog

  2. PPT

    assignment operator in prolog

  3. Prolog Operators

    assignment operator in prolog

  4. Swi prolog tutorial examples

    assignment operator in prolog

  5. PPT

    assignment operator in prolog

  6. Prolog Operator

    assignment operator in prolog

VIDEO

  1. Storing values with assignment operator

  2. Pyhton Assignment Operator #pythonoperators #assignmentoperators #pythonprogramming #pythontutorial

  3. Understanding ??= Null Coalescing Assignment Operator

  4. 6_Operator Assignment Relational LogicalBitwise

  5. Python Assignment Operator #python #assignmentoperators #pythonoperators #operatorsinpython

  6. ProgrammingAssignment2 Priyanka Perumalraja COP3330

COMMENTS

  1. How does = operator works in Prolog

    Lacking strings, there is no operator for string comparison. = is the unification operator. Unification is a big topic—not something that is easily summarized in a question, but as an approximation you can think of it as a bi-directional pattern matching. ... Prolog does not have assignment. True, you can give a variable a value. But you ...

  2. math

    This means that the operator =:= has precedence 700 and is of type xfx. This means that it is a binary infix operator. This means that you can, if you want, write a term like =:= (X, Y) equivalently as X =:= Y. In both cases, the functor of the term is =:=, and the arity of the term is 2.

  3. Prolog

    Comparison operators are used to compare two equations or states. Following are different comparison operators −. You can see that the '=<' operator, '=:=' operator and '=\=' operators are syntactically different from other languages. Let us see some practical demonstration to this.

  4. SWI-Prolog -- Operators

    4.25 Operators. Operators are defined to improve the readability of source code. For example, without operators, to write 2*3+4*5 one would have to write +(*(2,3),*(4,5)). In Prolog, a number of operators have been predefined. All operators, except for the comma (,) can be redefined by the user. Some care has to be taken before defining new ...

  5. PDF Arithmetic Operations in Prolog

    operators will be applied. Prolog achieves this by giving each operator a numerical precedence value. Operators with relatively high precedence such as * and / are applied before those with lower precedence such as + and -. Operators with the same precedence (e.g. + and -, * and /) are applied from left to right.

  6. Assign-once Variables

    Now having assign-once variables gives rise to a very interesting phenomenon: assignment can be symmetrical in Prolog. That is, Prolog doesn't have to treat the left and the right sides of an assignment differently, as must be done in normal procedural languages such as Pascal or C. ... As a matter of fact, Prolog doesn't have to treat tests ...

  7. Prolog Tutorial

    Arithmetic Operators. Prolog provides the standard arithmetic operations as summarized in the following table. SYMBOL : OPERATION + addition - subtraction * ... In this example it resembles an assignment operator however, it may not be used to reassign a variable to a new value. I the logical sense, the order of the clauses in the body of a ...

  8. Differences between unification and assignment operators.

    In Prolog '=' is the operator for term unification. On the other hand, in conventional programming languages ':=' is the operator for assigning values to variables. ... = is the assignment operator (for facts) = is equality test if both are bound variables or assignment if one is free. AI Rules! P. Top. Carlesius Posts: 6 Joined: 28 May 2016 19:38.

  9. Prolog Manual

    Prolog allows three types of operators: infix, prefix and postfix. Each operator has a precedence, which is a number from 1 to 1200. The precedence is used to disambiguate expressions where the structure of the term is not made explicit through the use of brackets. The general rule is that the operator with the highest precedence is the ...

  10. Introduction to Prolog

    Prolog supports user-defined operators, prefix, infix, and postfix, allowing the programmer to declare them and their precedences. This means that with proper operator declarations, Prolog syntax can be very flexible. With simple operator declarations Prolog can be made to process programs that look like natural language expressions.

  11. prolog arithmetic examples

    In Prolog, is the similar to the assignment operator = in other languages. X is 1+2 means assign the result 1+2 to the variable X. The following are some arithmetic operations performed in the prolog console window.

  12. PDF Intro to Prolog Chapter 11

    Predicates that are true for some assignment of values to their variables are called satisfiable. Those that are true for all possible assignments of values to their variables are called valid. A prolog program is essentially an implementation of predicate logic. Prolog Syntax Prolog is based on facts, rules, queries, constants, and variables.

  13. SWI-Prolog -- op/3

    op/3. current_op/3. Packages. Availability: built-in. [ISO]op ( +Precedence, +Type, :Name) Declare Name to be an operator of type Type with precedence Precedence. Name can also be a list of names, in which case all elements of the list are declared to be identical operators. Precedence is an integer between 0 and 1200.

  14. syntax in Prolog

    operator priorities and associativities Remarks. normal / structural / unification / arithmetic Univ operator but not using the C-like %-syntax Smalltalk: postfix operator new in PHP 5.4 in Scheme, not standard, but nearly standard Ruby >= 1.7

  15. Prolog

    Prolog is a logic programming language. It has important role in artificial intelligence. Unlike many other programming languages, Prolog is intended primarily as a declarative programming language. In prolog, logic is expressed as relations (called as Facts and Rules). Core heart of prolog lies at the logic being applied. Formulation or ...

  16. Operators in Prolog Language

    Assignment Operator: The is operator is used for variable assignment when performing arithmetic calculations. It assigns the result of an arithmetic expression to a variable. Example: ... Custom Operators: Prolog allows you to define your custom operators using the :- op/3 predicate. Custom operators can be used to improve the readability of ...

  17. append/3

    Use append/3 for substitution in a list. doc-needs-help. recurse down the backbone of List1 until [] has been reached. while doing so copy List1 element by element into a new list growing at the end. until the "empty cell" that is at the end of the backbone of the copied list can be unified with List2, creating a concatenated list with the ...

  18. Operators in Prolog

    The rules can also use the operator notation to aid readability. Some users of Prolog may find a rule like. likes (hary,A) :- is_female (A),owns (A,B), isa_dog (B). If the above rule is written as follow, it is easier to understand: hary likes A :- A is_female, A owns B, B isa_cat. If preferred, the operator can use the standard notation ...

  19. list

    Try the following unification at the Prolog prompt to illustrate: [1,2,3,4,5] = [H|T]. - lurker. May 30, 2017 at 10:03. ... A prolog assignment which uses lists. 4. Prolog Assignment. 1. Prolog instantiating variable to a list. 2. how to assign one list to a variable in prolog? 3.

  20. What's the -> operator in Prolog and how can I use it?

    3. It's a local version of the cut, see for example the section on control predicated in the SWI manual. It is mostly used to implement if-then-else by (condition -> true-branch ; false-branch). Once the condition succeeds there is no backtracking from the true branch back into the condition or into the false branch, but backtracking out of the ...

  21. SWI-Prolog -- Glossary of Terms

    Unlike assignment (which does not exist in Prolog), unification is not directed. ... 2001): "Eclipse Prolog provides two negation operators, one of which suspends itself on negative, non-ground atoms, hoping that their free variables will eventually become bound during the rest of the computation, at which point the operator resumes." ...