0% found this document useful (0 votes)
5 views13 pages

Unit 5 Ai

The document provides an overview of LISP, a programming language designed for AI, detailing its syntax, key features, and functions. It contrasts LISP with PROLOG, discusses input/output operations, local variables, recursion, and the significance of interaction in AI. Additionally, it covers property lists, arrays, and various non-deductive reasoning methods relevant to AI applications.

Uploaded by

iyonahpoloko
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views13 pages

Unit 5 Ai

The document provides an overview of LISP, a programming language designed for AI, detailing its syntax, key features, and functions. It contrasts LISP with PROLOG, discusses input/output operations, local variables, recursion, and the significance of interaction in AI. Additionally, it covers property lists, arrays, and various non-deductive reasoning methods relevant to AI applications.

Uploaded by

iyonahpoloko
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

UNIT 5

PROGRAMMING AND LOGICS IN AI


Introduction to LISP

What is LISP?

• LISP (LISt Processing) is one of the oldest programming languages, invented by John
McCarthy in 1958, mainly for Artificial Intelligence (AI) research.
• It emphasizes symbolic computation—the manipulation of symbols rather than
numbers.

Key Features:

• Everything in LISP is a list, including programs.


• LISP is functional, meaning functions are first-class citizens and can be passed as
arguments.
• Supports recursion and dynamic typing.
• Uses a REPL (Read-Eval-Print Loop) for interactive coding.

Syntax and Numerical Functions in LISP

Syntax Overview:

• LISP uses prefix notation (function comes first).


• Every instruction is an S-expression (Symbolic expression):
Format: (operator operand1 operand2 ...)

Examples:

(+ 2 3) ; 5
(- 7 4) ; 3
(* 3 4) ; 12
(/ 8 2) ; 4

Common LISP Functions:

• car: returns the first item of a list → (car '(1 2 3)) → 1


• cdr: returns the rest of the list → (cdr '(1 2 3)) → (2 3)
• cons: constructs a list → (cons 1 '(2 3)) → (1 2 3)
• list: creates a list → (list 1 2 3) → (1 2 3)
LISP and PROLOG Distinction

Aspect LISP PROLOG


Type Functional Language Logic Programming Language
Execution Explicit control flow Automatic backtracking
Goal Write algorithms/functions Define rules and facts
Paradigm Based on Lambda Calculus Based on Predicate Logic
Usage Symbolic manipulation, AI programs Expert systems, reasoning engines
Example (factorial 5) factorial (5, X).

• LISP is procedural and functional: you tell it how to do things.


• PROLOG is declarative: you tell it what you want, and it figures out how.

Input, Output, and Local Variables in LISP


Input in LISP

To take data from the user during program execution.

Function: read

• (read) is the basic input function in LISP.


• It reads a single LISP expression from the standard input.

Syntax:

(setq x (read))

Example:

(print "Enter a number: ")


(setq num (read))
(print num)

• read interprets input as a LISP expression, not just raw text.


• If you input 5, it is read as a number.
• If you input "hello", include quotes or it will be treated as a symbol.

Output in LISP

To display data or messages to the screen.


Common Output Functions:

Function Purpose Example


Prints a value and returns
print (print "Hello")
it
Prints without quotes or
princ (princ "Hello")
newline
terpri Prints a newline (terpri)
Formatted output like
format (format t "Name: ~a, Age: ~d~%" "Ali" 22)
printf
Examples:
(print "AI Programming") ; => "AI Programming"
(princ "No Quotes") ; => No Quotes
(terpri) ; New line
(format t "Sum: ~d~%" (+ 3 4)) ; => Sum: 7

• ~a, ~d, ~s are format specifiers (like in C):


• ~a: general output
• ~d: decimal number
• ~s: prints with string syntax

Local Variables in LISP

To define variables that are accessible only within a specific block or function.

Main Keyword: let

• let creates a block scope with local variables.


• Variables declared in let are not accessible outside it.

Syntax:

(let ((var1 value1)


(var2 value2))
expression1
expression2
...)
Example:
(let ((x 10)
(y 20))
(print (+ x y))) ; Output: 30
Nested Let Example:
(let ((x 5))
(let ((y 10))
(* x y))) ; Output: 50

Comparison: let vs setq


Feature let setq
Scope Local Global (or function-wide)
Variable reuse Allowed within block Overrides existing variable
Use case Temporary values in block General assignment

Example:

Program: Take 2 numbers from user and print their sum

(defun add-two-numbers ()
(print "Enter first number: ")
(setq a (read))
(print "Enter second number: ")
(setq b (read))
(let ((sum (+ a b)))
(format t "Sum is: ~d~%" sum)))

Call it using:

(add-two-numbers)

Interaction and Recursion

Interaction in LISP

In LISP, interaction refers to the real-time communication between the user and the
program using:

• Inputs (via read)


• Outputs (via print, format, etc.)
• Use of REPL (Read-Eval-Print Loop) for live command execution.

Tools for Interaction:


Function Purpose
read Accepts user input
print / princ Displays values to user
format Provides formatted output
read-line Reads a full line as string
Example: Interactive Greeting Program
(defun greet-user ()
(print "Enter your name:")
(setq name (read))
(format t "Hello, ~a!~%" name))
Output:
Enter your name:
"Alice"
Hello, Alice!
Role of Interaction in AI:

• Taking dynamic user inputs (like chatbot input, system preferences).


• Generating custom responses.
• Driving decision-making in rule-based or interactive expert systems.

Recursion in LISP

Recursion is a process where a function calls itself to solve a smaller part of a problem.

LISP is especially known for recursive programming due to:

• Its list-based structure


• Built-in support for tail recursion

General Structure of Recursion in LISP:


(defun function-name (params)
(if (base-case)
base-result
(recursive-case)))
Example 1: Factorial Function
(defun factorial (n)
(if (<= n 1)
1
(* n (factorial (- n 1)))))

(factorial 5) → 120

Example 2: Sum of List Elements


(defun sum-list (lst)
(if (null lst)
0
(+ (car lst) (sum-list (cdr lst)))))

(sum-list '(1 2 3 4 5)) → 15

Example 3: Fibonacci Sequence


(defun fibonacci (n)
(if (< n 2)
n
(+ (fibonacci (- n 1)) (fibonacci (- n 2)))))

(fibonacci 6) → 8

Why is Recursion Important in AI?


Use Case Reason
Tree Search AI decision trees use recursive traversal
List Processing Recursive functions process nested data
Backtracking Natural fit for recursive logic
Pattern Matching Recursively traverse symbolic patterns

Tail Recursion Optimization

LISP interpreters can optimize tail-recursive functions (where recursive call is the last
step).

Example:

(defun tail-factorial (n acc)


(if (= n 0)
acc
(tail-factorial (- n 1) (* acc n))))

📌 Call it like: (tail-factorial 5 1)

✔ Efficient, no extra stack frames → prevents stack overflow.

Recursion vs Iteration in LISP


Feature Recursion Iteration (loop, do)
Style Functional, elegant Procedural
Memory Uses call stack Uses loop variables
Readability Clean for tree/list problems Better for counting/indexing
Performance Tail recursion = efficient Usually faster for simple loops

Concept Description
Interaction Enables dynamic user-program communication using input/output
REPL Interactive environment for live LISP programming
Recursion A function calling itself to solve subproblems
Tail Recursion Optimized recursion with no stack overhead
Importance Essential for AI tasks like list processing, decision trees, etc.

Property List and Arrays

Property Lists (Plists)

A Property List (or plist) in LISP is a list that stores pairs of property names and values.
Each even indexed elementis a property name (keyword), and the next is its value.

Think of it like a dictionary or map:


(:property1 value1: property2 value2 ...)

Syntax:
(setq animal '(:name "Dog": sound "Bark": legs 4))

Here, :name: sound, and: legs are property keys, and "Dog", "Bark", and 4 are their
corresponding values.

Accessing Properties

Use the function:

(getf plist property-name)


Example:
(getf animal :name) ; => "Dog"
(getf animal :legs) ; => 4

Setting or Updating Properties

You can use setf with getf:

(setf (getf animal :legs) 3)

Now, (getf animal :legs) returns 3.


Example: Property List of a Book
(setq book '(:title "AI Fundamentals" :author "John Doe" :pages 300))

(format t "Title: ~a~%" (getf book :title))


(format t "Author: ~a~%" (getf book :author))

Advantages of Property Lists:


Advantage Description
Flexible Can grow/shrink easily
Human-readable Simple to understand and edit
No need for separate structure
Easy to use
definitions

Disadvantages of Property Lists:


Disadvantage Description
Slow for large datasets (linear
Not efficient
search)
Any key can be used without
No structure validation
checking
Easy to duplicate keys
Redundancy risk
unknowingly

Arrays in LISP

An array is a fixed-size indexed data structure used for efficient data access. LISP
supports 1D, 2D, and multi-dimensional arrays.

Creating Arrays

Use the function:

(make-array size)
Example (1D array):
(setq a (make-array 5))
This creates an array with 5 elements, all initially NIL.

Setting and Getting Array Elements

• Set element: (setf (aref array index) value)


• Access element: (aref array index)

Example:
(setf (aref a 0) 10)
(setf (aref a 1) 20)

(print (aref a 1)) ; => 20

Multi-dimensional Arrays
(setq matrix (make-array '(3 3))) ; 3x3 matrix

(setf (aref matrix 1 2) 9)


(print (aref matrix 1 2)) ; => 9
Initialize with Values
(setq nums (make-array 4 :initial-contents '(10 20 30 40)))
(print (aref nums 2)) ; => 30
Advantages of Arrays:
Advantage Description
Constant-time access via
Fast access
indices
Structured Fixed format and size
Supports matrix and grid
Multi-dimensional
operations

Disadvantages of Arrays:
Disadvantage Description
Fixed size Cannot resize after creation
Less flexible Compared to lists
Initialization needed Need to assign values or use initial-element

Alternative Languages for AI

Common AI Languages:

Language Strengths Use Cases


Python Easy syntax, huge libraries (TensorFlow, NLTK) NLP, ML, CV
PROLOG Rule-based logic programming Expert systems
Java OOP, portability Multi-agent systems
C++ Speed, low-level memory control Robotics, games
R Statistical computing AI in data science
Formalized Symbolic Logics

What is Symbolic Logic?

• A method of representing information through symbols and logical rules.

Types of Symbolic Logic:

1. Propositional Logic
a. Deals with simple, true/false statements
b. Example: A ∧ B → C
2. First-Order Logic (FOL)
a. Adds quantifiers and predicates
b. Example: ∀x (Human(x) → Mortal(x))
3. Second-Order Logic
a. Allows quantification over predicates/functions
b. More expressive, less decidable

Properties of WERS (Well-Engineered Rule-Based Systems)

What is WERS?

• A knowledge-based system using rules (IF-THEN) to make decisions.

Key Properties:

1. Modularity – Rules are independent; easy to add/update.


2. Transparency – Reasoning path is clear.
3. Maintainability – System can evolve as knowledge changes.
4. Soundness – Produces only correct conclusions.
5. Completeness – Produces all correct conclusions.
6. Efficiency – Fast reasoning using optimized engines.

Example:

IF fever AND cough THEN flu

Non-Deductive Inference Methods

What is Non-Deductive Inference?

Non-deductive inference refers to reasoning techniques where the conclusion is not


guaranteed to be true even if the premises are true. It deals with uncertain, incomplete, or
imperfect information.
Unlike deductive reasoning (which is exact and formal), non-deductive methods are
approximate but more practical for real-world AI problems.

Types of Non-Deductive Inference Methods


Inductive Reasoning: Reasoning from specific observations to general rules or hypotheses.
Example:

• Observation: "Sun rose today, yesterday, and the day before."


• Conclusion: "The sun rises every day."

Application in AI:

• Machine Learning algorithms (generalize from training data)


• Pattern recognition

Limitation:

• The conclusion may be false even if all observations are true.

2. Abductive Reasoning: Reasoning from an effect or observation to the most likely cause.

Example:

• Observation: "The grass is wet."


• Possible causes: "It rained," "Sprinklers were on," etc.
• Abduction: "Probably, it rained."

Application in AI:

• Medical diagnosis systems


• Fault detection in expert systems

Limitation:

• No guarantee the cause is correct; it's the best guess.

3. Default Reasoning: Making assumptions that are generally true unless proven
otherwise.

Example:

• "Birds can fly."


• If we know Tweety is a bird, we assume it can fly.
• But if we later learn Tweety is a penguin, we retract that assumption.

Application in AI:

• Default logic, non-monotonic reasoning


• Commonsense reasoning

Limitation:

• Requires mechanism to retract conclusions when new info appears.

4. Probabilistic Reasoning: Reasoning using probabilities to model uncertainty.

Example:

• If there’s an 80% chance it rains tomorrow, I’ll carry an umbrella.

Techniques:

• Bayesian Networks
• Markov Models
• Fuzzy logic systems

Application in AI:

• Speech recognition, natural language processing, robotics

Limitation:

• Requires prior probabilities and data to be meaningful.

5. Heuristic Reasoning: Using rules of thumb or educated guesses to make decisions.

Example:

• In a game: “Always protect your queen early.”


• In a search algorithm: Use a heuristic to estimate the goal distance.

Application in AI:

• A* search algorithm, planning, decision-making

Limitation:
• Heuristics may be inaccurate or misleading.

Comparison with Deductive Inference


Feature Deductive Inference Non-Deductive Inference
Truth Guarantee Always Not always
Use in AI Rule-based systems Uncertain or real-world reasoning
Formal logic needed Yes Often probabilistic or informal
Examples Modus Ponens, Resolution Induction, Abduction, Default logic

Why Non-Deductive Reasoning is Important in AI?

Reason Explanation
Real-world problems are uncertain We rarely have complete information
Deals with noise and ambiguity Useful in NLP, vision, decision-making
Enables learning from experience Machine learning relies on induction
Supports flexible decision-making AI systems need to revise beliefs

You might also like