==================== Prolog Tutorial ==================== Prolog, as the name itself suggests, is the short form of **LOGical PROgramming**. It is a logical and declarative programming language. Before diving deep into the concepts of Prolog, let us first understand what exactly logical programming is. Logic Programming ================= Logic Programming is one of the computer programming paradigms in which program statements express facts and rules about different problems within a system of formal logic. Rules are written in the form of logical clauses, where a *head* and a *body* are present. For example, if ``H`` is the head and ``B1``, ``B2``, ``B3`` are the elements of the body, then the rule states that ``H`` is true when ``B1``, ``B2``, and ``B3`` are all true. Facts are similar to rules but do not have a body. What Is Prolog? =============== Prolog (PROgramming in LOGics) is a logical and declarative programming language. It is a major example of a fourth-generation language that supports the declarative programming paradigm. Prolog is particularly suitable for programs involving symbolic or non-numeric computation. For this reason, it is widely used in Artificial Intelligence, where symbol manipulation and inference are fundamental tasks. Installing Prolog ================= To install Prolog on a Debian-based system: .. code-block:: console sudo apt update sudo apt install gprolog To start Prolog: .. code-block:: console gprolog Begin by practicing a basic *Hello World* program directly in the terminal: .. code-block:: prolog write('Hello World'). .. note:: Use single quotes, not double quotes, and end each command with a period. .. important:: The command ``halt.`` exits the Prolog environment. Creating Prolog Files ===================== File Naming Convention ---------------------- .. code-block:: console file_name.pl Each file should begin with: .. code-block:: prolog :- initialization(main). Write your code below this line. To compile and load the file: .. code-block:: prolog consult('file_name.pl'). Theory ====== Knowledge Base -------------- The knowledge base is one of the fundamental parts of logic programming. It stores facts and rules that describe relationships and properties within a problem domain. Facts, Rules, and Queries ------------------------- Facts, rules, and queries are the building blocks of logic programming. Facts ~~~~~ Facts define explicit relationships between objects and properties. Facts are unconditionally true. Examples: - Tom is a cat - Kunal loves to eat pasta - Hair is black - Nawaz loves to play games - Pratyusha is lazy Syntax: .. code-block:: prolog relation(object1, object2, ...). Example: .. code-block:: prolog cat(tom). loves_to_eat(kunal, pasta). of_color(hair, black). loves_to_play_games(nawaz). lazy(pratyusha). Rules ~~~~~ Rules define implicit relationships between objects. They are conditionally true: if the conditions on the right-hand side (*Body*) are true, then the left-hand side (*Head*) is also true. Examples: - Lili is happy if she dances - Tom is hungry if he searches for food - Jack and Bili are friends if both love cricket - He will go to play if school is closed and he is free Syntax notes: - ``:-`` is read as *if* or *is implied by* - Left-hand side is the *Head* - Right-hand side is the *Body* - Comma (`,`) represents conjunction - Semicolon (`;`) represents disjunction .. code-block:: prolog rule_name(object1, object2, ...) :- fact_or_rule(object1, object2, ...). Queries ~~~~~~~ Queries ask questions about relationships or properties. Examples: - Is Tom a cat? - Does Kunal love to eat pasta? - Is Lili happy? - Will Ryan go to play? Prolog evaluates queries and returns answers based on the knowledge base. Program Examples ================ Consider a knowledge base where Priya, Tiyasha, and Jaya are girls, and Priya can cook. .. literalinclude:: kb1.pl :language: prolog .. note:: Names must be lowercase. Identifiers beginning with uppercase letters are treated as variables in Prolog. Example queries: - Is Priya a girl? → Yes - Is Jamini a girl? → No - Can Priya cook? → Yes - Can Jaya cook? → No Another example using rules: .. literalinclude:: kb2.pl :language: prolog Interpretation: - Ananya sings → she listens to music - Rohit listens to music → he is happy - Queries resolve automatically based on defined rules Knowledge Base with Variables ============================= Variables begin with uppercase letters. When querying, Prolog returns results one at a time. Press ``;`` to see the next result. Code ---- .. literalinclude:: kb3.pl :language: prolog Command-Line Output ------------------- .. code-block:: console | ?- consult('D:/TP Prolog/Sample Codes/kb3.pl'). | ?- can_cook(X). X = priya ? ; X = jaya ? ; X = tiyasha. | ?- likes(priya, X). X = jaya ? ; X = tiyasha. Relations in Prolog =================== Prolog expresses relationships between objects and their properties. For example, the statement *Amit has a bike* expresses ownership. A query such as *Does Amit own a bike?* searches for that relationship. Relationships may be explicitly stated as facts or inferred through rules. Example: defining a *brother* relationship. Conditions: - Both are male - They share a parent .. code-block:: prolog parent(sudip, piyush). parent(sudip, raj). male(piyush). male(raj). brother(X, Y) :- parent(Z, X), parent(Z, Y), male(X), male(Y), X \= Y. Family Tree Example =================== Code ---- .. literalinclude:: family.pl :language: prolog Command-Line Output ------------------- .. code-block:: console | ?- parent(X, jim). X = pat ? ; X = peter. | ?- mother(X, Y). X = pam, Y = bob ? ; X = pat, Y = jim ? ; Data Objects ============ .. graphviz:: digraph data_objects { rankdir=TB; node [shape=box]; "Data Objects" -> "Simple Objects"; "Data Objects" -> "Structures"; "Simple Objects" -> "Constants"; "Simple Objects" -> "Variables"; "Constants" -> "Atoms"; "Constants" -> "Numbers"; } Atoms and Variables ==================== Atoms ----- Atoms are constants representing names or objects. Rules for atoms: - Begin with a lowercase letter - May include letters, digits, and underscores Examples: - ``azahar`` - ``b59`` - ``b_59AB`` - ``antara_sarkar`` Numbers ------- Numbers are another form of constants. Examples: - ``100`` - ``4`` - ``-81`` Typical integer range: ``-16383`` to ``16383`` Variables --------- Variables begin with an uppercase letter or underscore. Examples: - ``X`` - ``Sum`` - ``Student_List`` - ``_Temp`` Loops and Decision Making =========================== Loops ----- Prolog does not use traditional loop constructs like ``for`` or ``while``. Instead, repetition is achieved using recursion and predicates. Example loop using recursion: .. literalinclude:: loop.pl :language: prolog Output ~~~~~~ .. code-block:: console | ?- count_to_10(3). 3 4 5 6 7 8 9 10 true ? (47 ms) yes | ?- Loops Using ``between/3`` --------------------------- The ``between/3`` predicate can simulate looping with a range. .. literalinclude:: loop2.pl :language: prolog Output ~~~~~~ .. code-block:: console | ?- consult('D:/TP Prolog/Sample Codes/loop.pl'). compiling D:/TP Prolog/Sample Codes/loop.pl for byte code... D:/TP Prolog/Sample Codes/loop.pl compiled, 1 lines read - 1073 bytes written, 3 ms yes | ?- count_down(12,17). 5 true ? ; 4 true ? ; 3 true ? ; 2 true ? ; 1 true ? ; 0 (31 ms) yes | ?- count_up(5,12). 10 true ? ; 11 true ? ; 12 true ? ; 13 true ? ; 14 true ? ; 15 true ? ; 16 true ? ; 17 (47 ms) yes | ?- notes:: contue with decision making section and then finish part 1 part 2 will contain: operators lists built in predicates