This document provides a lab manual for an Artificial Intelligence laboratory course. It includes an index listing 9 experiments covering topics like Prolog programming, solving problems using Prolog like the 8-Queen problem, and optional content beyond the syllabus. The first experiment provides an overview of the Prolog language, covering basic terms, facts and rules, lists, recursion, and backtracking in Prolog.
The document discusses Python exception handling. It describes three types of errors in Python: compile time errors (syntax errors), runtime errors (exceptions), and logical errors. It explains how to handle exceptions using try, except, and finally blocks. Common built-in exceptions like ZeroDivisionError and NameError are also covered. The document concludes with user-defined exceptions and logging exceptions.
This document discusses classes and objects in C++. It defines a class as a user-defined data type that implements an abstract object by combining data members and member functions. Data members are called data fields and member functions are called methods. An abstract data type separates logical properties from implementation details and supports data abstraction, encapsulation, and hiding. Common examples of abstract data types include Boolean, integer, array, stack, queue, and tree structures. The document goes on to describe class definitions, access specifiers, static members, and how to define and access class members and methods.
Prolog is a logic programming language used for artificial intelligence and computational linguistics. It is declarative and logic is expressed through relations represented as facts and rules. A Prolog program consists of clauses that define relations, either facts with no body or rules with a head and body. Execution is initiated by a query, which tries to find a resolution refutation by using SLD resolution. Examples demonstrate writing to output, relations between family members, and an implementation of quicksort.
This document provides an introduction to finite automata. It defines key concepts like alphabets, strings, languages, and finite state machines. It also describes the different types of automata, specifically deterministic finite automata (DFAs) and nondeterministic finite automata (NFAs). DFAs have a single transition between states for each input, while NFAs can have multiple transitions. NFAs are generally easier to construct than DFAs. The next class will focus on deterministic finite automata in more detail.
It is related to Analysis and Design Of Algorithms Subject.Basically it describe basic of topological sorting, it's algorithm and step by step process to solve the example of topological sort.
The document discusses Python exception handling. It describes three types of errors in Python: compile time errors (syntax errors), runtime errors (exceptions), and logical errors. It explains how to handle exceptions using try, except, and finally blocks. Common built-in exceptions like ZeroDivisionError and NameError are also covered. The document concludes with user-defined exceptions and logging exceptions.
This document discusses classes and objects in C++. It defines a class as a user-defined data type that implements an abstract object by combining data members and member functions. Data members are called data fields and member functions are called methods. An abstract data type separates logical properties from implementation details and supports data abstraction, encapsulation, and hiding. Common examples of abstract data types include Boolean, integer, array, stack, queue, and tree structures. The document goes on to describe class definitions, access specifiers, static members, and how to define and access class members and methods.
Prolog is a logic programming language used for artificial intelligence and computational linguistics. It is declarative and logic is expressed through relations represented as facts and rules. A Prolog program consists of clauses that define relations, either facts with no body or rules with a head and body. Execution is initiated by a query, which tries to find a resolution refutation by using SLD resolution. Examples demonstrate writing to output, relations between family members, and an implementation of quicksort.
This document provides an introduction to finite automata. It defines key concepts like alphabets, strings, languages, and finite state machines. It also describes the different types of automata, specifically deterministic finite automata (DFAs) and nondeterministic finite automata (NFAs). DFAs have a single transition between states for each input, while NFAs can have multiple transitions. NFAs are generally easier to construct than DFAs. The next class will focus on deterministic finite automata in more detail.
It is related to Analysis and Design Of Algorithms Subject.Basically it describe basic of topological sorting, it's algorithm and step by step process to solve the example of topological sort.
The document discusses various Python datatypes. It explains that Python supports built-in and user-defined datatypes. The main built-in datatypes are None, numeric, sequence, set and mapping types. Numeric types include int, float and complex. Common sequence types are str, bytes, list, tuple and range. Sets can be created using set and frozenset datatypes. Mapping types represent a group of key-value pairs like dictionaries.
The document discusses recursion and lists in Prolog. It covers recursive definitions, clause ordering and termination, lists, members, and recursing down lists. Recursive definitions allow a predicate to refer to itself in its own definition. Clause ordering can impact termination and procedural meaning. Lists are a fundamental recursive data structure in Prolog, consisting of elements separated by commas and enclosed in brackets. The member predicate checks if an element is in a list by recursively working down the list. Recursing down lists is common for tasks like comparing lists or copying elements between lists.
The document discusses finite automata including nondeterministic finite automata (NFAs) and deterministic finite automata (DFAs). It provides examples of NFAs and DFAs that recognize particular strings, including strings containing certain substrings. It also gives examples of DFA state machines and discusses using finite automata to recognize regular languages.
This document provides an overview of deterministic finite automata (DFA) through examples and practice problems. It begins with defining the components of a DFA, including states, alphabet, transition function, start state, and accepting states. An example DFA is given to recognize strings ending in "00". Additional practice problems involve drawing minimal DFAs, determining the minimum number of states for a language, and completing partially drawn DFAs. The document aims to help students learn and practice working with DFA models.
The document defines and describes various graph concepts and data structures used to represent graphs. It defines a graph as a collection of nodes and edges, and distinguishes between directed and undirected graphs. It then describes common graph terminology like adjacent/incident nodes, subgraphs, paths, cycles, connected/strongly connected components, trees, and degrees. Finally, it discusses two common ways to represent graphs - the adjacency matrix and adjacency list representations, noting their storage requirements and ability to add/remove nodes.
A presentation on prim's and kruskal's algorithmGaurav Kolekar
This slides are for a presentation on Prim's and Kruskal's algorithm. Where I have tried to explain how both the algorithms work, their similarities and their differences.
This document provides an introduction and outline for a course on Formal Language Theory. The course will cover topics like set theory, relations, mathematical induction, graphs and trees, strings and languages. It will then introduce formal grammars including regular grammars, context-free grammars and pushdown automata. The course is divided into 5 chapters: Basics, Introduction to Grammars, Regular Languages, Context-Free Languages, and Pushdown Automata. The Basics chapter provides an overview of formal vs natural languages and reviews concepts like sets, relations, functions, and mathematical induction.
This document discusses trees and their applications in discrete mathematics. It begins with an introduction to trees, including defining different types of trees such as rooted trees, m-ary trees, and binary trees. It then covers applications of trees such as binary search trees, decision trees, and game trees. Next, it discusses different tree traversal algorithms like preorder, inorder, and postorder traversal and how they can be used to represent expressions. Finally, it provides examples of evaluating expressions represented as trees.
An array is a data structure that stores fixed number of items of the same type. It allows fast access of elements using indices. Basic array operations include traversing elements, inserting/deleting elements, searching for elements, and updating elements. Arrays are zero-indexed and elements are accessed via their index.
This slide is prepared By these following Students of Dept. of CSE JnU, Dhaka. Thanks To: Nusrat Jahan, Arifatun Nesa, Fatema Akter, Maleka Khatun, Tamanna Tabassum.
The document discusses graph traversal algorithms breadth-first search (BFS) and depth-first search (DFS). It provides examples of how BFS and DFS work, including pseudocode for algorithms. It also discusses applications of BFS such as finding shortest paths and detecting bipartitions. Applications of DFS include finding connected components and topological sorting.
This document provides an overview of trees as a non-linear data structure. It begins by discussing how trees are used to represent hierarchical relationships and defines some key tree terminology like root, parent, child, leaf, and subtree. It then explains that a tree consists of nodes connected in a parent-child relationship, with one root node and nodes that may have any number of children. The document also covers tree traversal methods like preorder, inorder, and postorder traversal. It introduces binary trees and binary search trees, and discusses operations on BSTs like search, insert, and delete. Finally, it provides a brief overview of the Huffman algorithm for data compression.
The solution to the single-source shortest-path tree problem in graph theory. This slide was prepared for Design and Analysis of Algorithm Lab for B.Tech CSE 2nd Year 4th Semester.
Semantic networks are a knowledge representation technique where concepts are represented as nodes in a graph, and relationships between concepts are represented as links between nodes. There are different types of semantic networks, including definitional networks that emphasize subclass relationships, assertional networks for making propositions, and executable networks that can change based on operations. Common semantic relations include IS-A for subclasses, INSTANCE for examples, and HAS-PART for components. While semantic networks provide a natural representation of relationships, they have disadvantages like lack of standard link names and difficulty representing some logical constructs.
C tokens are the basic building blocks of a C program and include keywords, identifiers, constants, separators, and operators. There are five types of tokens: keywords which have fixed meanings; identifiers which are user-defined names; constants which are fixed values; separators which separate statements; and operators which perform operations. Some examples of tokens in C are keywords like int, identifiers like x, y, separators like { and }, and operators like +.
Automata theory studies abstract computing devices and the types of tasks they are capable of. Alan Turing pioneered this field in the 1930s by studying Turing machines. The theory examines questions like which tasks can and cannot be performed by different models of machines. It also considers the distinction between what is computable versus the complexity of computation. Common concepts include finite automata, formal languages, and the Chomsky hierarchy for classifying language types. Proofs in automata theory involve techniques like deduction, induction, contradiction, and establishing results by definition.
In this module of python programming you will be learning about control statements. A control statement is a statement that determines whether other statements will be executed. An if statement decides whether to execute another statement, or decides which of two statements to execute. A loop decides how many times to execute another statement.
This document discusses propositional logic and knowledge representation. It introduces propositional logic as the simplest form of logic that uses symbols to represent facts that can then be joined by logical connectives like AND and OR. Truth tables are presented as a way to determine the truth value of propositions connected by these logical operators. The document also discusses concepts like models of formulas, satisfiable and valid formulas, and rules of inference like modus ponens and disjunctive syllogism that allow deducing new facts from initial propositions. Examples are provided to illustrate each concept.
The document discusses recursion and lists in Prolog. It covers recursive definitions, clause ordering and termination, lists, members, and recursing down lists. Recursive definitions allow a predicate to refer to itself in its own definition. Clause ordering can impact termination and the procedural meaning. Lists are a fundamental data structure that can contain other lists as elements. The member predicate checks if an item is in a list by recursively working down the list. Recursing down lists is common for tasks like comparing lists or copying elements.
UOS-BSIT-3811-Artificial-Intelligence-Introduction-to-prolog-PDF.pptxqasim ali
Prolog is a logic programming language intended primarily for declarative programming. In Prolog, programs logic is expressed through relations represented as facts and rules. A computation is initiated by running a query over these relations. Prolog has a single data type, the term, which can be atoms, numbers, variables, lists, or compound terms. Atoms are general names while numbers can be integers or floats. Variables are placeholders and compound terms combine a functor and arguments. Lists represent ordered collections of terms. Special compound terms include strings.
The document discusses various Python datatypes. It explains that Python supports built-in and user-defined datatypes. The main built-in datatypes are None, numeric, sequence, set and mapping types. Numeric types include int, float and complex. Common sequence types are str, bytes, list, tuple and range. Sets can be created using set and frozenset datatypes. Mapping types represent a group of key-value pairs like dictionaries.
The document discusses recursion and lists in Prolog. It covers recursive definitions, clause ordering and termination, lists, members, and recursing down lists. Recursive definitions allow a predicate to refer to itself in its own definition. Clause ordering can impact termination and procedural meaning. Lists are a fundamental recursive data structure in Prolog, consisting of elements separated by commas and enclosed in brackets. The member predicate checks if an element is in a list by recursively working down the list. Recursing down lists is common for tasks like comparing lists or copying elements between lists.
The document discusses finite automata including nondeterministic finite automata (NFAs) and deterministic finite automata (DFAs). It provides examples of NFAs and DFAs that recognize particular strings, including strings containing certain substrings. It also gives examples of DFA state machines and discusses using finite automata to recognize regular languages.
This document provides an overview of deterministic finite automata (DFA) through examples and practice problems. It begins with defining the components of a DFA, including states, alphabet, transition function, start state, and accepting states. An example DFA is given to recognize strings ending in "00". Additional practice problems involve drawing minimal DFAs, determining the minimum number of states for a language, and completing partially drawn DFAs. The document aims to help students learn and practice working with DFA models.
The document defines and describes various graph concepts and data structures used to represent graphs. It defines a graph as a collection of nodes and edges, and distinguishes between directed and undirected graphs. It then describes common graph terminology like adjacent/incident nodes, subgraphs, paths, cycles, connected/strongly connected components, trees, and degrees. Finally, it discusses two common ways to represent graphs - the adjacency matrix and adjacency list representations, noting their storage requirements and ability to add/remove nodes.
A presentation on prim's and kruskal's algorithmGaurav Kolekar
This slides are for a presentation on Prim's and Kruskal's algorithm. Where I have tried to explain how both the algorithms work, their similarities and their differences.
This document provides an introduction and outline for a course on Formal Language Theory. The course will cover topics like set theory, relations, mathematical induction, graphs and trees, strings and languages. It will then introduce formal grammars including regular grammars, context-free grammars and pushdown automata. The course is divided into 5 chapters: Basics, Introduction to Grammars, Regular Languages, Context-Free Languages, and Pushdown Automata. The Basics chapter provides an overview of formal vs natural languages and reviews concepts like sets, relations, functions, and mathematical induction.
This document discusses trees and their applications in discrete mathematics. It begins with an introduction to trees, including defining different types of trees such as rooted trees, m-ary trees, and binary trees. It then covers applications of trees such as binary search trees, decision trees, and game trees. Next, it discusses different tree traversal algorithms like preorder, inorder, and postorder traversal and how they can be used to represent expressions. Finally, it provides examples of evaluating expressions represented as trees.
An array is a data structure that stores fixed number of items of the same type. It allows fast access of elements using indices. Basic array operations include traversing elements, inserting/deleting elements, searching for elements, and updating elements. Arrays are zero-indexed and elements are accessed via their index.
This slide is prepared By these following Students of Dept. of CSE JnU, Dhaka. Thanks To: Nusrat Jahan, Arifatun Nesa, Fatema Akter, Maleka Khatun, Tamanna Tabassum.
The document discusses graph traversal algorithms breadth-first search (BFS) and depth-first search (DFS). It provides examples of how BFS and DFS work, including pseudocode for algorithms. It also discusses applications of BFS such as finding shortest paths and detecting bipartitions. Applications of DFS include finding connected components and topological sorting.
This document provides an overview of trees as a non-linear data structure. It begins by discussing how trees are used to represent hierarchical relationships and defines some key tree terminology like root, parent, child, leaf, and subtree. It then explains that a tree consists of nodes connected in a parent-child relationship, with one root node and nodes that may have any number of children. The document also covers tree traversal methods like preorder, inorder, and postorder traversal. It introduces binary trees and binary search trees, and discusses operations on BSTs like search, insert, and delete. Finally, it provides a brief overview of the Huffman algorithm for data compression.
The solution to the single-source shortest-path tree problem in graph theory. This slide was prepared for Design and Analysis of Algorithm Lab for B.Tech CSE 2nd Year 4th Semester.
Semantic networks are a knowledge representation technique where concepts are represented as nodes in a graph, and relationships between concepts are represented as links between nodes. There are different types of semantic networks, including definitional networks that emphasize subclass relationships, assertional networks for making propositions, and executable networks that can change based on operations. Common semantic relations include IS-A for subclasses, INSTANCE for examples, and HAS-PART for components. While semantic networks provide a natural representation of relationships, they have disadvantages like lack of standard link names and difficulty representing some logical constructs.
C tokens are the basic building blocks of a C program and include keywords, identifiers, constants, separators, and operators. There are five types of tokens: keywords which have fixed meanings; identifiers which are user-defined names; constants which are fixed values; separators which separate statements; and operators which perform operations. Some examples of tokens in C are keywords like int, identifiers like x, y, separators like { and }, and operators like +.
Automata theory studies abstract computing devices and the types of tasks they are capable of. Alan Turing pioneered this field in the 1930s by studying Turing machines. The theory examines questions like which tasks can and cannot be performed by different models of machines. It also considers the distinction between what is computable versus the complexity of computation. Common concepts include finite automata, formal languages, and the Chomsky hierarchy for classifying language types. Proofs in automata theory involve techniques like deduction, induction, contradiction, and establishing results by definition.
In this module of python programming you will be learning about control statements. A control statement is a statement that determines whether other statements will be executed. An if statement decides whether to execute another statement, or decides which of two statements to execute. A loop decides how many times to execute another statement.
This document discusses propositional logic and knowledge representation. It introduces propositional logic as the simplest form of logic that uses symbols to represent facts that can then be joined by logical connectives like AND and OR. Truth tables are presented as a way to determine the truth value of propositions connected by these logical operators. The document also discusses concepts like models of formulas, satisfiable and valid formulas, and rules of inference like modus ponens and disjunctive syllogism that allow deducing new facts from initial propositions. Examples are provided to illustrate each concept.
The document discusses recursion and lists in Prolog. It covers recursive definitions, clause ordering and termination, lists, members, and recursing down lists. Recursive definitions allow a predicate to refer to itself in its own definition. Clause ordering can impact termination and the procedural meaning. Lists are a fundamental data structure that can contain other lists as elements. The member predicate checks if an item is in a list by recursively working down the list. Recursing down lists is common for tasks like comparing lists or copying elements.
UOS-BSIT-3811-Artificial-Intelligence-Introduction-to-prolog-PDF.pptxqasim ali
Prolog is a logic programming language intended primarily for declarative programming. In Prolog, programs logic is expressed through relations represented as facts and rules. A computation is initiated by running a query over these relations. Prolog has a single data type, the term, which can be atoms, numbers, variables, lists, or compound terms. Atoms are general names while numbers can be integers or floats. Variables are placeholders and compound terms combine a functor and arguments. Lists represent ordered collections of terms. Special compound terms include strings.
Prolog, Prolog Programming IN AI. Prolog is an Artificial Intelligence programming language. Prolog is a logic programming language associated with artificial intelligence and computational linguistics. Its applications include natural language understanding and expert systems. Prolog is notably a so-called nonprocedural, or declarative, language.
First-order logic (FOL) is a formal system used in mathematics, philosophy, linguistics, and computer science to represent knowledge about domains involving objects and relations. FOL extends propositional logic with quantifiers and predicates to describe properties of and relations between objects. Well-formed formulas in FOL involve constants, variables, functions, predicates, quantifiers, and logical connectives. The meaning and truth of FOL statements is determined with respect to a structure called a model that specifies a domain of objects and interpretations of symbols. FOL can be used to represent knowledge about many different domains and perform logical inference.
1. Domain Specific Modelling can be viewed as a form of theory building, where a domain is understood by developing theories about it consisting of true statements.
2. Traditionally, programming is seen as implementing a theory, but modelling languages treat the domain weakly and lack support for truly representing theories.
3. The paper proposes enhancing modelling languages to more fully support domain theories, including defining syntax, semantics, and mappings between theories and implementations.
This document provides an overview of the Prolog programming language. It begins with an outline of the topics that will be covered, including syntax of terms, simple programs, terms as data structures, the cut operator, and writing real programs. It then defines Prolog as a logic programming language that uses logical variables and unification. The rest of the document explains key aspects of Prolog like clauses, facts, rules, queries, compound terms, and unification through examples. It also discusses how Prolog programs are executed and how clauses can be read both declaratively and procedurally.
Prolog Programming is a document about the Prolog programming language. It discusses key features of Prolog such as logical variables, unification, backtracking, defining procedures with clauses, and using Prolog as a relational database. It provides examples of Prolog code including simple programs involving terms, facts, and rules. It also covers syntax of Prolog terms and compound terms, and how Prolog interprets clauses both declaratively and procedurally.
The document discusses different methods of representing knowledge in artificial intelligence systems, including formal logic, production rules, and structured objects like semantic networks and frames. It provides examples of representing statements in propositional and predicate calculus, and how logic-based languages like Prolog can be used for knowledge representation and reasoning. Semantic networks are introduced as a way to organize knowledge representation in a graph-like structure similar to how human memory works.
This document provides an overview of first-order logic for knowledge representation in artificial intelligence. It discusses the syntax and semantics of first-order logic, including predicates, quantifiers, and variables. It also describes the knowledge engineering process for developing a first-order logic knowledge base, including identifying the problem domain, encoding general domain knowledge as rules, and representing a specific problem instance. Queries can then be posed to the knowledge base to infer answers using logical reasoning techniques like forward chaining and backward chaining.
This document provides an introduction to first-order logic (FOL) including motivation, syntax, semantics, and examples. It discusses how FOL allows statements about relationships between objects using predicates, constants, variables, and quantifiers. Interpretations assign meanings to symbols and determine whether formulas are true or false. Validity and entailment are defined in terms of interpretations satisfying formulas.
The document discusses context-free grammars (CFG) and their efficient implementation using difference lists, a Prolog technique. It explains how difference lists represent grammatical categories as the difference between two lists, allowing a sentence to be recognized by consuming the symbols in one list and leaving the symbols in the other list. The document then presents a CFG recognizer implemented using this difference list approach. It also introduces Definite Clause Grammars (DCGs) as an alternative notation for writing grammars as Prolog programs.
This document provides an introduction to the syntax of first-order logic. It begins by discussing the main objects of study in mathematical logic, such as set theory and number theory. It then defines the components of a first-order language, including logical symbols (variables, connectives, quantifiers), non-logical symbols (constants, functions, relations) and terms. Terms correspond to algebraic expressions and are formed from variables, constants and functions. Examples of languages for set theory, group theory and the theory of rings are provided.
1. Hash tables are good for random access of elements but not sequential access. When records need to be accessed sequentially, hashing can be problematic because elements are stored in random locations instead of consecutively.
2. To find the successor of a node in a binary search tree, we take the right child. This operation has a runtime complexity of O(1).
3. When comparing operations like insertion, deletion, and searching between different data structures, arrays generally have the best performance for insertion and searching, while linked lists have better performance for deletion and allow for easy insertion/deletion anywhere. Binary search trees fall between these two.
The document discusses syntax, semantics, and intended meaning in symbol systems. It defines:
- Syntax as symbols and rules for composition into structures
- Semantics as the relationship between syntax and intended meaning
- Intended meaning as truths about the world that the symbol system represents
It then summarizes key concepts in logic programming including terms, substitutions, instances, queries, rules, and the declarative and operational semantics of logic programs.
The first official version of Prolog was developed in the 1970s in France as a tool for programming in logic. Today, Prolog is used for artificial intelligence applications like knowledge bases, expert systems, and natural language interfaces. Visual Prolog addresses the same market as SQL databases, C++, and other programming languages.
This document introduces a new data modelling approach and compares it to traditional relational database models. It provides definitions and examples of key concepts in relational modelling like entities, attributes, relations, and constraints. It also demonstrates various ways to represent these constructs in Wolfram Language, including as lists, associations, graphs, and RDF triplets. The goal is to help software developers and data modellers learn the advantages of applying this new method.
The document discusses the key differences between the English and mathematics languages, including how words, symbols, and concepts have different meanings or representations. It explains how mathematics has developed a precise symbolic language to concisely express relationships, operations, and concepts in a way that is internationally understood regardless of spoken language. Precise definitions and notations are provided for important mathematical concepts like sets, relations, functions, and equations.
This document discusses representing data types and programming in an abstract way that hides the concrete representation of data. It presents an approach where programs operate on abstract representations of data rather than concrete implementations, allowing computations to be performed without inspecting the output. As an example, it shows an abstract implementation of list concatenation that computes correctly without knowing the concrete list representation. This approach ensures correctness while preventing inspection of results.
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTjpsjournal1
The rivalry between prominent international actors for dominance over Central Asia's hydrocarbon
reserves and the ancient silk trade route, along with China's diplomatic endeavours in the area, has been
referred to as the "New Great Game." This research centres on the power struggle, considering
geopolitical, geostrategic, and geoeconomic variables. Topics including trade, political hegemony, oil
politics, and conventional and nontraditional security are all explored and explained by the researcher.
Using Mackinder's Heartland, Spykman Rimland, and Hegemonic Stability theories, examines China's role
in Central Asia. This study adheres to the empirical epistemological method and has taken care of
objectivity. This study analyze primary and secondary research documents critically to elaborate role of
china’s geo economic outreach in central Asian countries and its future prospect. China is thriving in trade,
pipeline politics, and winning states, according to this study, thanks to important instruments like the
Shanghai Cooperation Organisation and the Belt and Road Economic Initiative. According to this study,
China is seeing significant success in commerce, pipeline politics, and gaining influence on other
governments. This success may be attributed to the effective utilisation of key tools such as the Shanghai
Cooperation Organisation and the Belt and Road Economic Initiative.
Introduction- e - waste – definition - sources of e-waste– hazardous substances in e-waste - effects of e-waste on environment and human health- need for e-waste management– e-waste handling rules - waste minimization techniques for managing e-waste – recycling of e-waste - disposal treatment methods of e- waste – mechanism of extraction of precious metal from leaching solution-global Scenario of E-waste – E-waste in India- case studies.
International Conference on NLP, Artificial Intelligence, Machine Learning an...gerogepatton
International Conference on NLP, Artificial Intelligence, Machine Learning and Applications (NLAIM 2024) offers a premier global platform for exchanging insights and findings in the theory, methodology, and applications of NLP, Artificial Intelligence, Machine Learning, and their applications. The conference seeks substantial contributions across all key domains of NLP, Artificial Intelligence, Machine Learning, and their practical applications, aiming to foster both theoretical advancements and real-world implementations. With a focus on facilitating collaboration between researchers and practitioners from academia and industry, the conference serves as a nexus for sharing the latest developments in the field.
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesChristina Lin
Traditionally, dealing with real-time data pipelines has involved significant overhead, even for straightforward tasks like data transformation or masking. However, in this talk, we’ll venture into the dynamic realm of WebAssembly (WASM) and discover how it can revolutionize the creation of stateless streaming pipelines within a Kafka (Redpanda) broker. These pipelines are adept at managing low-latency, high-data-volume scenarios.
Using recycled concrete aggregates (RCA) for pavements is crucial to achieving sustainability. Implementing RCA for new pavement can minimize carbon footprint, conserve natural resources, reduce harmful emissions, and lower life cycle costs. Compared to natural aggregate (NA), RCA pavement has fewer comprehensive studies and sustainability assessments.
Recycled Concrete Aggregate in Construction Part III
AI Lab Manual.docx
1. EASWARI ENGINEEING COLLEGE
(Autonomous Institution)
Department of Artificial Intelligence and Data Science
LAB MANUAL
191AIC412L - Artificial Intelligence Laboratory
Year/Semester: II / IV Academic Year: 2021-2022
Prepared By:
Mrs.K.P.Revathi,AP/AI&DS.
2. EASWARI ENGINEEING COLLEGE
Department of Artificial Intelligence and Data Science
INDEX
S.No Practical’s Name
1 Study of Prolog.
2 Write simple fact for the statements using PROLOG.
3
Write predicates One converts centigrade temperatures to Fahrenheit, the other
checks if a temperature is below freezing.
4 Write a program to solve the Monkey Banana problem.
5
WAP in turbo prolog for medical diagnosis and show t he
advantage and disadvantage of green and red cuts.
6 WAP to implement factorial, Fibonacci of a given number.
7 Write a program to solve 8-Queen problem.
8 Write a program to solve traveling salesman problem.
9 Write a program to solve water jug problem using prolog
Content Beyond the Syllabus
C1 Write a PROLOG Program to generate query based on family relationship
C2 Write a PROLOG/C program to implement an Expert System of your choice.
3. EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 1
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: Study of Prolog.
Prolog
Prolog is a general purpose logical programming language associated with artificial intelligence and
computational linguistics and has its roots in formal logic.
The language was first conceived by a group around Alain Colmerauer in Marseille, France, in the early
1970s and the first Prolog system was developed in 1972 by Colmerauer with Philippe Roussel.
Prolog was one of the first logic programming languages, and remains among the most popular such
languages today, with many free andcommercial implementations available. While initially aimed at naturallanguage
processing, the language has since then stretched far into other areas like theorem proving, expert systems, games,
automated answering systems, ontologies and sophisticated control systems. Modern Prolog environments support
the creation of graphical user interfaces, as well as administrative and networked applications. Most computer
languages are basedon the stepsneeded to solve a problem. The Prolog language, on the other hand, is a "declarative"
language which indicates the logical relationships between entities. The program logic is expressed in terms of
relations, represented as facts and rules. A computation is initiated by running a query over these relations.
Basic characters (symbols) of Prolog
Upper-case letters : A, B, ...,Z;
Lower-case letters :a, b, ...,z;
Digits : 1, 2, ...,9;
Special characters :+, -, *, /, <, >, =, :, ., &, ~, and _.
Terms
Facts,rules, and queries are built out of terms and there are four kinds of terms in Prolog: atoms, numbers,
variables, and complex terms (or structures). Atoms and numbers are lumped together under the heading constants,
and constants and variables together make up the simple terms of Prolog.
Atoms
4. Atom refers to any specific thing in Prolog. Atoms typically make up the domain of the problem under
consideration. Syntactically, atoms may be constructed as
A string of characters made up of upper-case letters, lower-case letters, digits, and the
underscore character, that begins with a lower-case letter. For example monkey, desk, etc.
An arbitrary sequence of character enclosed in single quotes. For example 'Vincent', ‘The king’, etc. The
character between the single quotes is called the atom name.
A string of special characters. For example: @= and ====>
Numbers
Numbers can be floats or integers.
Variables
A variable is used to represent an arbitrary element from some domain. For example, in the relation parent(X,
Y), X and Y are variables representing arbitrary people from a family. Within a Prolog program, variables typically
occur in the arguments of relations and functions. Syntactically, a variable is a string of upper-case letters,lower-case
letters, digits and underscore characters that starts either with an upper-case letter or with underscore. For example,
X, Y, List24, _head, Tail, _input and Output are all Prolog variables.
Complex terms (or Structures)
A complex term is composed of an atom called a "functor" and a number of "arguments", which are again terms.
Complex terms are ordinarily written as a functor followed by a comma-separated list of argument terms, which is
contained in parentheses.The number of arguments is called the term's arity. An atom canbe regardedas a compound
term with arity zero. Examples of complex terms are friends(maria,jim)and mother(sally,sam).
Facts and queries
Facts either consist of a particular item or a relation between items. For example we can represent that it is sunny by
writing the fact :
sunny.
We can now ask a query of Prolog by asking
?- sunny.
?- is the Prolog prompt. To this query, Prolog will answer true because Prolog matches it in its database of facts.
Facts should always begin with a lowercase letter and end with a full stop. The facts themselves can consist of any
letter or number combination, as well as the underscore _ character. Facts can have arbitrary number of arguments
from zero upwards. A general model is shown below:
relation(<argument1>,<argument2>,....,<argumentN> ).
The arguments can be any legal Prolog term.
Example: eats(fred,oranges).
eats(tony,apple).
eats(john,apple).
5. Sample queries:
?- eats(fred,oranges).
True.
?- eats(john,apple).
True.
?- eats(mike,apple).
False.
Rules
Consider the sentence : 'All men are mortal'. This sentence can be represented in Prolog by a rule as :
mortal(X) :- human(X).
The clause can be read as 'X is mortal if X is human'.
If one has to define the fact that Socrates is a human it can be written as:
mortal(X) :- human(X).
human(socrates).
Now if we ask to prolog :
?- mortal(socrates).
Prolog will respond :
yes
In order to solve the query -? mortal(socrates). Prolog will use the rule we have given. It says that in order to prove
that someone is mortal we can prove that he is human. So from the goal mortal(socrates) Prolog generates the
subgoal human(socrates).
If one wants to know who is mortal :
?- mortal(X).
Then Prolog should respond :
X=socrates
This means that Prolog was able to answer the query by unifying the variable X to socrates.
Lists
List is an important recursive data structure widely used in computational linguistics. It is denoted by square
brackets with the terms separated by commas or in the case of the empty list, []. For example [1,2 ,3] or [red, green,
blue].
General syntax of a list:
[t1; t2; : : : ; tn]
where each ti is a Prolog term. A term in a list may be another list. The first term t1 is called the head of the list. The
remaining part of the list, [t2; : : : ; tn] is called the tail.
Lists can be used to represent sets although there is a difference. The order of elements in a set does not matter
6. while the order of items in a list does. Also, the same object can occur repeatedly in a list. Still, the most common
operations on lists are similar to those on sets. They are
checking whether some object is an element of a list, which corresponds to checking for the set membership
concatenation of two lists, obtaining a third list, which corresponds to the union of sets;
Adding a new object to a list, or deleting some object from it.
List operations
Membership
The membership relation can be implemented as member( X, L) where X is an object and L is a list. The
goal member(X, L) is true if X occurs in L.
For example, member( b, [a,b,c] ) returns true but member( b, [a,[b,c]] ) returns false whereas member([b,c],
[a,[b,c]]) returns true.
Generally, X is a member of L if either
(1) X is the head of L, or
(2) X is a member of the tail of L.
This can be written in two clauses (the first is a simple fact and the second is a rule):
member( X, [X | Tail] ).
member( X, [Head | Tail) :-
member( X, Tail).
Concatenation
Concatenation relation is defined as: conc( Ll, L2,L3) . Here Ll andL2 are two lists, and L3 is their concatenation.
For example: conc( [a,b], [c,d], [a,b,c,d] ) returns true.
We have two cases:
(1) If the first argument is the empty list then the second and the third arguments must be the same list (L). This is
expressed by the following Prolog fact:
conc( [], L, L).
(2) If the first argument of conc is a non-empty list then it has a head and a tail and must look like this: [X | L1].
Hence rule for concatenation is:
conc([X | L1], L2, [X | L3]) :-
conc(L1,L2,L3).
Adding an item to the list
If X is the new item and the list to which X is added is L then the fact to be written for addition is : add(X,L,[ X | L
]).
Deleting an item:
7. The del relation can be defined similarly to the membership relation.
(1) If X is the head of the list then the result after the deletion is the tail of the list.
(2) If X is in the tail then it is deleted from there.
del( X, [X I Tail], Tail).
del( X, [Y I Tail], [Y I Tail1] ) :-
del( X, Tail, Tail1).
Sublist generation
S is a sublist of L if
(1) L can be decomposed into two lists, Ll and L2, and
(2) L2 can be decomposed into two lists, S and some L3.
sublist(S,L):-
conc(L1,L2,L),
conc(S,L3,L2).
Permutations
The program for permutation is based on the consideration of two cases:
(1) If the first list is empty then the second list must also be empty.
(2) If the first list is not empty then it has the form [X I L], first permute L obtaining L1 and then insert X at any
position into L1.
permutation([],[]).
permutation([X|L],P):-
permutation(L,L1).
insert(X,L1,P).
Reversing A List
Reversing a list can be implemented by the following prolog clauses:
reverse([],[]).
reverse([First|Rest],Reversed):-
reverse(Rest,RestReversed),
conc(RestReversed,[First],Reversed).
Palindrome Check
palindrome(List) :- reverse(List,List).
Length Of the List
The length of a list can be obtained by the following prolog clauses:
8. length([],0).
length([_|Tail],N):-
length(Tail,N1),
N is 1 + N1.
Sum of the Elements in a List
sumlist([],0).
sumlist([H|Tail],Sum):-
sumlist(Tail,Sum1),
Sum is H + Sum1.
Selecting From a List
select(a,[a,b,a,c],L).
select(a,L,[b,c,d]).
Prolog Computation Tree
It is a tree that is constructed and (depth-first) searched through by the prolog interpreter in order to satisfy
(answer) goals (queries).
Unification
Prolog proves goals by matching patterns of a query goal with the patterns of the clauses of a Prolog program. It
does this by finding a clause whose head matches the query goal and then trying to prove the goals, if any, in the
clause's body.
Prolog has to have a method for matching the goal it is currently trying to prove against heads of clauses. When
the head of a clause and the current goal match, the clause is chosen and Prolog goes on to try and prove the goals in
its body (if any).
The act of matching two Prolog terms is called unification and is described by the following rules:
1. Two atoms unify if they are the same.
2. Two numbers unify if they have the same value.
3. Two structures unify if they have the same name and arity, and each pair of respective arguments unify.
4. Two lists unify if their initial elements unify, and the lists which remain after removing both initial elements unify.
5. A variable unifies with a non-variable by being replaced by the non-variable. This is known as binding.
6. Two variables unify by agreeing to "share" bindings. This means that if later on, one or the other unifies with another
term, then both unify with the term.
7. Two strings unify if and only if they have precisely the same characters in them.
8. A string and an atom will unify if they have precisely the same characters in them.
9. 9. When a clause is under consideration to match against a goal, space is reservedto hold variable bindings. If the clause
is chosen again later on in the proof, then new space is reserved for the variable bindings caused by the new choice.
Unification with Occurs check
Consider the following query:
father(X) = X.
With old Prolog implementations a message will be displayed as:
Not enough memory to complete query!
and a long string of symbols like:
X=father(father(father(father(father(father(father(father(father(father(father(father(father
(father(father(father(father(father(father(father(father(father(father(father(father(father
(father(father(father(father(father(father(father(father(father
Prolog desperately tries to match these terms, but doesn’t succeed. The variable X, which occurs as an
argument to a functor on the left hand side, and on its own on the right hand side, makes matching impossible.
But the current Prolog implementations have found a way of overcoming this problem. When the query father(X)
= X is posed to SICStus Prolor or SWI. The answer will be : X = father(father(father(father(father(father(...))))))))))
The dots indicate that there is an infinite nesting of fatherfunctors. So, newerversions of Prolog can detectcycles
in terms without running out of memory and have a finite internal representation of such infinite terms.
However, a standard unification algorithm works differently. When a unification query with terms that refer to
impossible nested combinations is given, it causes the unification algorithm to go in an infinite loop, thus crashing
the system. Instead,if the Prolog flag occurs_check is turned on, then attempts to unify cyclic terms will simply fail,
rather than crash. But, Matching is one of the fundamental processes that makes Prolog work, so it needs to be carried
out as fast as possible. Carrying out an occurs check every time matching was called for would slow it down
considerably. Hence the standard default setting for the occurs check is off.
unify_with_occurs_check(X,Y) attempts to unify X and Y in the normal way, but also guards against unification
of cyclic terms, which could cause a system crash. ISO Prolog implementations have the built-in predicate
unify_with_occurs_check for sound unification. Implementations offering sound unification for all unifications
(optionally, via a runtime flag) are ECLiPSe and SWI-Prolog.
Backtracking
Prolog uses unification to match a goal to the head of a clause, but if there are severalcandidate clauses, Prolog
has to make a decision as to which one to try first. Prolog's backtracking top-to-bottom, left-to-right search provides
a simple and effective solution in such situations. Backtracking works as follows:
1. If Prolog cannot prove a sub-goal in the body of a clause, then it looks at the sub-goal immediately to its left. If there
are any other clauses which can be used to re-prove this goal, then any variable bindings which resulted from the
previous clause selection are discarded, and Prolog continues with the new proof.
10. 2. If the sub-goal which initially failed was the first goal in the body of the clause, then the whole goal fails, and the
backtracking continues in the parent clause (the clause containing the reference to the goal whose proof just failed).
Backtracking is a very powerful tool since it will try and generate a solution by automated search.
Control over backtracking
Automatic backtracking is one of the most characteristic features of Prolog. But backtracking can lead to
inefficiency. Sometimes Prolog can waste time exploring possibilities that lead nowhere. It would be better to have
some control over this aspect of its behaviour.
Cut operator
The inbuilt Prolog predicate !, called cut, offers a direct method to control backtracking. the cut operator is an
atom. If Prolog finds a cut in a rule, it will not backtrackon the choices it has made.This is illustrated by the following
program
a(X, Y) :- b(X), !, c(Y).
b(1).
b(2).
b(3).
c(1).
c(2).
c(3).
If we ask Prolog ?- a(Q, R). it will first answer
?- a(Q, R).
Q = 1
R = 1 ;
And when we ask Prolog for more answers, using the ;-key:
Q = 1
R = 2 ;
Q = 1
R = 3 ;
False
Hence it can be seen that Prolog considers 1 as the only option for Q, whereas it returns all alternatives for R.
Collecting solutions
Sometimes we would like to have all the solutions to a query, and we would like them handed to us in a neat,
usable, form. Prolog has three built-in predicates that do this: findall, bagof, and setof.
findall(Instance, Goal, List)
findall succeedsif List canbe unified with the list of all instances of Instance making Goal provable. For example,
findall(X, a(X), [1, 2, 3]) is true if the logicbase contains the following clauses for a:
a(1).
a(2).
11. a(3).
If Goal cannot be proved for any values of Instance, then List is unified with the empty list []. findall is generally
used to generate lists from logicbase entries, so for example it might be used as follows:
?- findall(X, a(X), L).
L = [1, 2, 3].
bagof(Instance, Goal, List)
bagof is like findall except in the way it deals with variables occurring in Goal which are not in Instance. These
are known as free variables. In this case, bagof is backtrackable into and produces one list for each possible binding
of the free variables.
setof(Instance, Goal, List)
setof is like bagof except that the list is sorted according to the standard order and any duplicates are removed.
Control facilities
not(Goal) not succeeds if and only if Goal cannot be proved.
fail is a goal that always fails.
true is a goal that always succeeds
call( P) invokes a goal P. It succeeds if P succeeds.
once(Goal) The predicate once behaves like call except it is only executed once. This is useful for isolating code that
we don't intend to be backtracked into, and makes for more readable code than inserting lots of cuts (!).
catch(GOAL, ERROR, HANDLER)
catch catches any errors that unify with ERROR thrown during the execution of GOAL. If an error is caught,
control passes to HANDLER. If no errors are caught, catch is the same as call. catch catches errors thrown by
the application, using throw/1, or errors thrown by the system. System errors are thrown
as error structures:
error(ERROR_CLASS, ATTRIBUTE_VALUE_LIST)
The ATTRIBUTE_VALUE_LIST will vary depending on the type of error.
throw(TERM)
throw throws and error, and the error is TERM. TERM can be any valid Prolog term. If TERM unifies with the
ERROR argument of a catch above the throw in the call stack, then that catch HANDLER will handle the error.
repeat is a goal that always succeeds. Its special property is that it is non deterministictic. Therefore, each time it is
reached by backtracking it generates another alternative execution branch. repeat behaves as if defined by:
repeat.
repeat :- repeat.
for(Index, Start, End, Increment)
for provides a shorthand for implementing repeat/fail loops that execute a prespecified number of times. Bottom, Top
12. and Increment must be bound to integers with Bottom being less than or equal to Top. When first proved, Index is
unified with Bottom and checked to see whether it is less than or equal to Top. If so, for succeeds otherwise it fails.
On backtracking Increment is added to the current value of Index and Index is bound to this new value. Again a range
check is performed.
?- for(X, 1, 5, 1), write(X), fail.
12345
False.
Operators
Arithmetic operators
For the arithmetic operators, prolog has already a list of predefined predicates. These are :
=,is,<,>,=<,>=,==,=:=,/,*,+,-,mod,div
In Prolog, the calculations are not the same as the usual representation. They are written as a binary tree. For
example: 2*a + b*c is written as +(*(2,a), *(b,c)) and is represented as:
Since we would normally prefer to have such expressions written in the usual infix form, Prolog caters for this
notational convenience and will therefore accept the expression written simply as: 2*a + b*c.
Nevertheless,the rules of priority on the operators should be mentioned. For instance, we have to say to Prolog
that * is prior on +.We have also to indicate to Prolog the prior calculations with '()'. Prolog allows one to define
one’s own operators with the relations of the form:
Op(P,xfy,name). Where P is the priority of the operators(between 1 and 1200), xfy indicates if the operator is
infix(xfx,xfy,yfx) or postfix(fx,fy). The name is the name of the operator. The prior operator has the lowest priority.
Prolog has already these predefined operators:
Op(1200,xfx,':-').
Op(1200,fx,[:-,?-]).
Op(1100,xfy,';').
Op(1000,xfy,',').
Op(700,xfx,[=,is,<,>,=<,>=,==,=:=]).
Op(500,yfx,[+.-]).
Op(500,fx,[+,-,not]).
Op(400,yfx,[*,/,div]).
Op(300,xfx,mod).
Arithmetic computations
13. Prolog use the infix operator 'is' to give the result of an arithmetic operation to a variable.
X is 3 + 4.
Prolog responds
X = 7
Yes
Comparison operators
The arithmetic comparison operators are :<=<>>==:=/=
X<Y True if X is less than Y.
X=<Y True if X is less than or equal to Y.
X>Y True if X is greater than Y.
X>= True if X is greater than or equal to Y.
X=:=Y True if X is equal to Y.
X=/=Y True if the values of X and Y are not equal
The term comparison operators are :@<@=<@>@>=
X@<Y The term X is less than Y
Y@=<Y The term X is less than or equal to Y
X@>Y The term X is greater than Y
X@>=Y The term X is greater or equal to Y
The term order from the lowest to the highest is :
1. Variables.
2. Floating point numbers.
3. Integers.
4. atoms in the alphabetical order.
Logical ‘and’ operator
X , Y
Logical 'and' is represented by the comma operator ','. It succeeds if both X and Y both can be proved, else it
fails. The comma used to separate goals is an operator, and syntactically very different from the comma used to
separate the arguments of a structure, or elements of a list.
Logical ‘or’ operator
X ; Y
Logical 'or' is represented by the semicolon operator, ';'/2. It succeeds if Xcan be proved or Y can be proved; else
it fails.
Goal1 -> Goal2 ; Goal3
Goal1 -> Goal2 ; Goal3 is an if-then-else construct. If Goal1 can be proved then Prolog tries to prove Goal2.
14. Otherwise if Goal1 fails Prolog tries to prove Goal3. Goal1 is not backtrackable into once it has been proved.
Input and Output Commands
Sometimes a program will need to read a term from a file or the keyboard and write a term on the screen or in a
file. The various predicates used for this purpose are:
read(X) : Read the term from the active input and unify X with it.
write(Y) : Write the term Y on the active output.
see(Filename) : Open for output the file with the name Filename.
seeing(File) : When File is a variable, File is unified with the name of the input file.
seen : Close the current input file.
tell(Fillename) : Open the file for output.
telling(File) : File is unified to the name of the output file.
told : Close the current output file.
Recursion
The recursion in any language is a function that can call itself until the goal has been achieved. In Prolog,
recursion appears when a predicate contains a goal that refers to itself. When a rule is called Prolog creates a
new query with new variables. So it makes no difference whether a rule calls another rule or calls itself. In Prolog
and in any language, a recursive definition always has at least two parts. A first fact that acts like a stopping condition
and a rule that calls itself. At each level the first fact is checked. If the fact is true then the recursion ends. If not the
recursion continues. Arecursive rule must never call itself with the same arguments. If that happens then the program
will never end.
Example of a recursive program in Prolog: (Factorial)
factoriel(0,1).
factoriel(X,Y) :-
X1 is X - 1,
factoriel(X1,Z),
Y is Z*X,!.
Now if we enter :
?- factoriel(5,X).
X = 120
True
In this example Prolog will try to calculate 5! then 4! then 3! until it has to calculate 0!, then the result
will be 0!*1*2*3*4*5. Prolog will respond 120. Here, the cut ! is not necessary, since there is only one
solution. The message ''Out of local stack'' may appear if one presses ';' after the first solution.
15. SWI PROLOG
SWI-Prolog
SWI-Prolog is an open source implementation of the programming language Prolog, commonly used for
educational purposes and semantic web applications. It has a rich set of features, libraries for constraint logic
programming, multithreading, unit testing, GUI, interfacing to Java,ODBC and others, literate programming, a web
server,SGML, RDF,RDFS, developer tools (including an IDE with a GUI debugger and GUI profiler), and extensive
documentation.
IDE
The SWI-Prolog editor 5.6.64 provides a user-friendly environment for editing, compiling and debugging Prolog
codes and maintains all coding standards.
Compiling a Prolog program
There are two ways to compile a program. One way is to select the Consult command from the Start menu. The
other method is to give a query of the form:
?- ['C:/Program Files/pl/demo/likes']
(OR)
?- ['C:Program Filespldemolikes']
Instead of using the ‘Consult’ option if the ‘Consult all’ option is used then all the programs loaded currently
into the editor will be compiled.
Tracing a Prolog program
The flow of control of a Prolog program canbe tracedusing the ‘Trace on/off’ option from the Test menu. Tracing
16. a program can help us detect any anomalous behaviour in the program.
In the same way, the option ‘Debug on/off’ can be used to debug the goals following it. The option GUI-tracer
is the same as trace,but forces the use of the graphical (source-level) debugger.
Other Commands of SWI-Prolog
The option ‘Breakpoints on/off’ from the Test menu can be used to set breakpoints for the process of verifying the
flow of logic of the program. Once the breakpoints are turned on and a query is given, the graphical debugger screen
opens and the operations and the change of variable values can be viewed.
The option ‘Clear breakpoints’ from the Test menu removes all the breakpoints which are currently active.
The command ‘Retry query’ from the Start menu retriggers the goal which was most recently triggered.
17. The command ‘Abort’ from the Start menu aborts the current execution of a program.
The command ‘Restart’ from the Start menu clears the screen of the query engine.
The ‘Search’ command from the Edit menu shows the location of a particular word or symbol in the program. It
works like the ‘find’ option in text files.
The ‘Replace’ command from the Edit menu is synonymous to the ‘Find and Replace’ option of the text files.
The ‘Indent’ option from the Edit menu aligns the selected text with indentation and the ‘Comment’ option converts
the selected text into a comment line.
Conclusion
Thus the study of the features of Prolog programming language has been performed.
18. EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 2
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: Write simple fact for following:
a. Ram likes mango.
b. Seema is a girl.
c. Bill likes Cindy.
d. Rose is red.
e. John owns gold.
f. john is son of mary
g. john is a boy if he is son of mary
h. pizza is a food
Program:
Clauses
likes(ram ,mango).
girl(seema).
red(rose).
likes(bill ,cindy).
owns(john ,gold).
son(john,mary).
boy(john) :- son(john,mary).
food(pizza).
Output:
Goal
queries
?-likes(ram,What).
What= mango
?-likes(Who,cindy).
Who= cindy
?-red(What).
What= rose
?-owns(Who,What).
Who= john
What= gold.
?-john(Who).
Who=son of mary
?- food(pizza).
Result: Thus the PROLOGprogram about simple facts were executed and its output is verified successfully.
19. EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 3
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: Write predicates One converts centigrade temperatures to
Fahrenheit, the other checks if a temperature is below freezing.
Program:
Production rules:
Arithmetic:
c_to_f f is c * 9 / 5 +32
freezing f < = 32
Rules:
c_to_f(C,F) :-
F is C * 9 / 5 + 32.
freezing(F) :-
F =< 32.
Output:
Queries:
?- c_to_f(100,F).
F = 212
Yes
?- freezing(15)
.Yes
?- freezing(45).
No
2b.: Below student-professor relation table shows the facts, rules, goals and their english meanings.
Facts English meanings
studies(charlie, csc135). // charlie studies csc135
studies(olivia, csc135). // olivia studies csc135
studies(jack, csc131). // jack studies csc131
studies(arthur, csc134). // arthur studies csc134
teaches(kirke, csc135). // kirke teaches csc135
teaches(collins, csc131). // collins teaches csc131
teaches(collins, csc171). // collins teaches csc171
teaches(juniper, csc134). // juniper teaches csc134
Rules
20. professor(X, Y) :-
teaches(X, C), studies(Y,
C).
// X is a professor of Y if
X teaches C and Y studies
C.
Queries / Goals
?- studies(charlie, What).
// charlie studies what?
OR
What does charlie study?
?- professor(kirke,
Students).
// Who are the students of
professor kirke.
Result: Thus the PROLOGprogram about arithmetic operations were executed and its output is verified successfully.
21. EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 4
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: Write a program to solve the Monkey Banana problem.
Imagine a room containing a monkey, chair and some bananas. That have been hanged from
the center of ceiling. If the monkey is clever enough he can reach the bananas by placing the
chair directly below the bananas and climb on the chair. The problem is to prove the monkey
can reach the bananas. The monkey wants it, but cannot jump high enough from the floor. At
the window of the room there is a box that the monkey can use. The monkey can perform the
following actions:-
1) Walk on the floor.
2) Climb the box.
3) Push the box around (if it is beside the box).
4) Grasp the banana if it is standing on the box directly under the banana.
Production Rules
can_reach clever,close.
get_on: can_climb.
under in room,in_room, in_room,can_climb.
Close get_on,under| tall
Parse Tree
Clauses:
in_room(bananas).
in_room(chair).
in_room(monkey).
clever(monkey).
can_climb(monkey, chair).
tall(chair).
22. can_move(monkey, chair, bananas).
can_reach(X, Y):-
clever(X),close(X, Y).
get_on(X,Y):- can_climb(X,Y).
under(Y,Z):-
in_room(X),in_room(Y),in_room(Z),can_climb(X,Y,Z).
close(X,Z):-get_on(X,Y),
under(Y,Z);
tall(Y).
Output:
Queries:
?- can_reach(A, B).
A = monkey.
B = banana.
?- can_reach(monkey, banana).Yes.
Result: Thus the PROLOGprogram Monkey Banana problem was executed and its output is verified successfully.
23. EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 5
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: WAP in turbo prolog for medical diagnosis and show the advantage and
disadvantage of green and red cuts.
ALGORITHM:
1. Start
2. First the knowledge is encoded in knowledge base
3. A set of new questions are raised to the users
4. Matching the answers convert personality is returned
5. No match occur error message displayed
6. Stop.
Program:
disease(y,y,y,y):-write('You are suffering from VIRAL FEVER').
disease(y,y,y,n):-write('You are suffering from COMMON FEVER').
disease(y,y,n,y):-write('You are suffering from VIRAL FEVER').
disease(y,y,n,n):-write('You maybe OVERHOOKED').
disease(y,n,y,y):-write('You are suffering from COLD').
disease(y,n,y,n):-write('You might develop THROAT INFECTION').
disease(y,n,n,y):-write('You might have SEDENTARY for a long spell').
disease(y,n,n,n):-write('You are suffering from HEADACHE').
disease(n,y,y,y):-write('You are suffering from FEVER').
disease(n,y,y,n):-write('You are experiencing initial stages of COMMON COLD').
disease(n,y,n,y):-write('You are suffering from DEHYDRATION').
disease(n,y,n,n):-write('You are suffering from DENGU FEVER').
disease(n,n,y,y):-write('You are suffering from CHICKENGUNYA').
disease(n,n,y,n):-write('You are suffering from SORE THROAT').
disease(n,n,n,y):-write('You can relax, U are ENERVATED').
24. disease(n,n,n,n):-write('You are ALRIGHT').
run:-
write('Do you have HEADACHE?'),
read(HA),
write('Do you have TEMPARATURE?'),
read(TP),
write('Do you have a SORE THROAT?'),
read(ST),
write('Are you feeling TIRED?'),
read(TR),
disease(HA,TP,ST,TR).
Sample Input and Output:
1 ?-
% c:/Documents and Settings/Administrator/My Documents/Prolog/r.pl compiled 0.00 sec, 2,476 bytes
1 ?- run.
Do you have HEADACHE? y.
DO you have TEMPERATURE? y.
Do you have a SORE THROAT? y.
Are you feeling TIRED? y.
You are suffering from VIRAL FEVER
true
RESULT:
Thus the PROLOG program to diagnose the disease is executed and its output is verified successfully.
25. EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 6
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: WAP to implement factorial, fibonacci of a given number.
Program:
Factorial:
factorial(0,1).
factorial(N,F) :-
N>0,
N1 is N-1,
factorial(N1,F1),
F is N * F1.
Output:
Goal:
?- factorial(4,X).
X=24
Fibonacci:
fib(0, 0).
fib(X, Y) :- X > 0, fib(X, Y, _).
fib(1, 1, 0).
fib(X, Y1, Y2) :-
X > 1,
X1 is X - 1,
fib(X1, Y2, Y3),
Y1 is Y2 + Y3.
Output:
Goal:
?-fib(10,X).
X=55
RESULT:
Thus the PROLOG program to implement factorial, fibonacci of a given number were executed and its
output is verified successfully.
26. EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 7
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: Write a program to solve N-Queen problem.
Flow-Chart:
27. Algorithm:
Start
Step 1: Represent the board position as 8*8 vector, i.e., [1,2,3,4,5,6,7.8]. Store the set
ofqueens in the list ‘Queens’.
Step 2: Calculate the permutation of the above eight numbers stored in set P.
Step 3: Let the position where the first queen to be placed be(1,Y), for second be
(2,Y1),and so on and store the position in S.
Step 4: Check for the safety of the queens through the predicate, ‘noattack()’.
Step 5: Calculate Y1-y and Y-Y1. If both are not equal to Xdist, which is the X-
distance between the first queen and others, then goto step 6 else goto step 7.
Step 6: Increment Xdist by 1.
Step 7: Repeat above for the rest of the queens, until the end of the list is
reached.Step 8: Print S as answer.
Stop
Program:
domains
H,F,I,Y,Y1,Xdist,Dist1,Queen=integer
T,L,L1,PL,PT,Queen,Others=integer*
predicates
safe(L)
solution(L)
permutation(L,L
)del(I,L,L)
noattack(I,L,L)
clauses
solution(Queens):-
permutation([1,2,3,4,5,6,7,8],Queens),
safe(Queens).
permutation([],[]).
permutation([H|T],PL):-
permutation(T,PT),
del(H,PT,PI).
del(I,[I|L],L).
del(I,[F|L,[F|L1]):-
del(I,L,L1).
safe([]).
safe([Queen|Others]):-
safe(Others),
noattack(Queen,Others,1).
noattack(_,[],_).
29. EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 8
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: Write a program to solve traveling salesman problem.
The following is the simplified map used for the prototype:
Program:
Production Rules:-
route(Town1,Town2,Distance) road(Town1,Town2,Distance).
route(Town1,Town2,Distance)
road(Town1,X,Dist1),route(X,Town2,Dist2),Distance=Dist1+Dist2,
domains
town = symbol
distance = integer
predicates
nondeterm road(town,town,distance)
nondeterm route(town,town,distance)
clauses
road("tampa","houston",200).
road("gordon","tampa",300).
road("houston","gordon",100).
road("houston","kansas_city",120).
31. EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 9
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: Write a program to solve water jug problem.
ALGORITHM:
1. Start.
2. Initialize the node and place the root node in queue and mark is visited.
3. Remove the first node from the queue and find its success and mark it as visited.
4. Place the visited node in queue.
5. Stop.
Program:
waterjug(G,H,P,_,_,G,H):- write('Path:'),write(.([G,H],P)),!,true.
waterjug(X,Y,_,MaxX,MaxY,_,_):-(X>MaxX;Y>MaxY),!,fail.
waterjug(X,Y,_,_,_,_,_):-g_read(visited,V),member([X,Y],V),!,fail.
waterjug(X,Y,P,MaxX,MaxY,G,H):-
X>0,g_read(visited,V),g_assign(visited,.([X,Y],V)),waterjug(0,Y,.([X,Y],P),MaxX,MaxY,G,H).
waterjug(X,Y,P,MaxX,MaxY,G,H):-
Y>0,g_read(visited,V),g_assign(visited,.([X,Y],V)),waterjug(X,0,.([X,Y],P),MaxX,MaxY,G,H).
waterjug(X,Y,P,MaxX,MaxY,G,H):-X>0,Y<MaxY,X>=(MaxY-
Y),g_read(visited,V),g_assign(visited,.([X,Y],V)),N1 is X-(MaxY-
Y),waterjug(N1,MaxY,.([X,Y],P),MaxX,MaxY,G,H).
waterjug(X,Y,P,MaxX,MaxY,G,H):-X>0,Y<MaxY,X<(MaxY-
Y),g_read(visited,V),g_assign(visited,.(([X,Y]),V)),N1 is
X+Y,waterjug(0,N1,.([X,Y],P),MaxX,MaxY,G,H).
waterjug(X,Y,P,MaxX,MaxY,G,H):-X<MaxX,Y>0,Y>=(MaxX-
X),g_read(visited,V),g_assign(visited,.(([X,Y]),V)),N1 is Y-(MaxX-
X),waterjug(MaxX,N1,.([X,Y],P),MaxX,MaxY,G,H).
waterjug(X,Y,P,MaxX,MaxY,G,H):-X<MaxX,Y>0,Y<(MaxX-
X),g_read(visited,V),g_assign(visited,.(([X,Y]),V)),N1 is
X+Y,waterjug(N1,0,.([X,Y],P),MaxX,MaxY,G,H).
35. Ex 2: An Expert System
Aim:- Write a PROLOG/C program to implement an Expert System of your choice.
Program:-
domains
disease,indication = symbol
Patient,name = string
Predicates
hypothesis(string,disease)
symptom(name,indication)
response(char)
go
clauses
go :-
write("What is the patient's name? "),
readln(Patient),
hypothesis(Patient,Disease),
write(Patient,"probably has ",Disease,"."),nl.
go :-
write("Sorry, I don't seem to be able to"),nl,
write("diagnose the disease."),nl.
symptom(Patient,fever) :-
write("Does ",Patient," have a fever (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,rash) :-
write("Does ",Patient," have a rash (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,headache) :-
write("Does ",Patient," have a headache (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,runny_nose) :-
write("Does ",Patient," have a runny_nose (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,conjunctivitis) :-
write("Does ",Patient," have a conjunctivitis (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,cough) :-
36. write("Does ",Patient," have a cough (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,body_ache) :-
write("Does ",Patient," have a body_ache (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,chills) :-
write("Does ",Patient," have a chills (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,sore_throat) :-
write("Does ",Patient," have a sore_throat (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,sneezing) :-
write("Does ",Patient," have a sneezing (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,swollen_glands) :-
write("Does ",Patient," have a swollen_glands (y/n) ?"),
response(Reply),
Reply='y'.
hypothesis(Patient,measles) :-
symptom(Patient,fever),
symptom(Patient,cough),
symptom(Patient,conjunctivitis),
symptom(Patient,runny_nose),
symptom(Patient,rash).
hypothesis(Patient,german_measles) :-
symptom(Patient,fever),
symptom(Patient,headache),
symptom(Patient,runny_nose),
symptom(Patient,rash).
hypothesis(Patient,flu) :-
symptom(Patient,fever),
symptom(Patient,headache),
symptom(Patient,body_ache),
symptom(Patient,conjunctivitis),
symptom(Patient,chills),
symptom(Patient,sore_throat),
symptom(Patient,runny_nose),
symptom(Patient,cough).