[go: up one dir, main page]

0% found this document useful (0 votes)
347 views62 pages

Artificial Intelligence Notes

The document provides an overview of artificial intelligence (AI), including: 1) It defines AI as creating intelligent machines and computer programs that can think like humans by studying how the human brain works. 2) The goals of AI are to create expert systems that exhibit intelligent behavior and implement human intelligence in machines to understand, think, learn, and behave like humans. 3) AI techniques help organize vast amounts of knowledge that is constantly changing in a way that is understandable, modifiable, and useful even if the knowledge is incomplete or inaccurate. This elevates the speed of complex AI programs.

Uploaded by

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

Artificial Intelligence Notes

The document provides an overview of artificial intelligence (AI), including: 1) It defines AI as creating intelligent machines and computer programs that can think like humans by studying how the human brain works. 2) The goals of AI are to create expert systems that exhibit intelligent behavior and implement human intelligence in machines to understand, think, learn, and behave like humans. 3) AI techniques help organize vast amounts of knowledge that is constantly changing in a way that is understandable, modifiable, and useful even if the knowledge is incomplete or inaccurate. This elevates the speed of complex AI programs.

Uploaded by

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

UNIT 1

General Issues and Overview of AI


Since the invention of computers or machines, their capability to perform various tasks went on
growing exponentially. Humans have developed the power of computer systems in terms of their
diverse working domains, their increasing speed, and reducing size with respect to time.

A branch of Computer Science named Artificial Intelligence pursues creating the computers or
machines as intelligent as human beings.

What is Artificial Intelligence?


According to the father of Artificial Intelligence, John McCarthy, it is “The science and
engineering of making intelligent machines, especially intelligent computer programs”.

Artificial Intelligence is a way of making a computer, a computer-controlled robot, or a


software think intelligently, in the similar manner the intelligent humans think.

AI is accomplished by studying how human brain thinks, and how humans learn, decide, and
work while trying to solve a problem, and then using the outcomes of this study as a basis of
developing intelligent software and systems.

Philosophy of AI
While exploiting the power of the computer systems, the curiosity of human, lead him to wonder,
“Can a machine think and behave like humans do?”

Thus, the development of AI started with the intention of creating similar intelligence in
machines that we find and regard high in humans.

Goals of AI
 To Create Expert Systems − The systems which exhibit intelligent behavior, learn,
demonstrate, explain, and advice its users.
 To Implement Human Intelligence in Machines − Creating systems that understand,
think, learn, and behave like humans.

What Contributes to AI?


Artificial intelligence is a science and technology based on disciplines such as Computer
Science, Biology, Psychology, Linguistics, Mathematics, and Engineering. A major thrust of AI
is in the development of computer functions associated with human intelligence, such as
reasoning, learning, and problem solving.

Out of the following areas, one or multiple areas can contribute to build an intelligent system.

Programming Without and With AI


The programming without and with AI is different in following ways −

Programming Without AI Programming With AI


A computer program without AI can answer the A computer program with AI can answer the
specific questions it is meant to solve. generic questions it is meant to solve.
AI programs can absorb new modifications by
putting highly independent pieces of
Modification in the program leads to change in
information together. Hence you can modify
its structure.
even a minute piece of information of program
without affecting its structure.
Modification is not quick and easy. It may lead
Quick and Easy program modification.
to affecting the program adversely.

What is AI Technique?
In the real world, the knowledge has some unwelcomed properties −

 Its volume is huge, next to unimaginable.


 It is not well-organized or well-formatted.
 It keeps changing constantly.

AI Technique is a manner to organize and use the knowledge efficiently in such a way that −

 It should be perceivable by the people who provide it.


 It should be easily modifiable to correct errors.
 It should be useful in many situations though it is incomplete or inaccurate.

AI techniques elevate the speed of execution of the complex program it is equipped with.

Applications of AI
AI has been dominant in various fields such as −

 Gaming − AI plays crucial role in strategic games such as chess, poker, tic-tac-toe, etc.,
where machine can think of large number of possible positions based on heuristic
knowledge.
 Natural Language Processing − It is possible to interact with the computer that
understands natural language spoken by humans.
 Expert Systems − There are some applications which integrate machine, software, and
special information to impart reasoning and advising. They provide explanation and
advice to the users.
 Vision Systems − These systems understand, interpret, and comprehend visual input on
the computer. For example,
o A spying aeroplane takes photographs, which are used to figure out spatial
information or map of the areas.
o Doctors use clinical expert system to diagnose the patient.
o Police use computer software that can recognize the face of criminal with the
stored portrait made by forensic artist.
 Speech Recognition − Some intelligent systems are capable of hearing and
comprehending the language in terms of sentences and their meanings while a human
talks to it. It can handle different accents, slang words, noise in the background, change
in human’s noise due to cold, etc.
 Handwriting Recognition − The handwriting recognition software reads the text written
on paper by a pen or on screen by a stylus. It can recognize the shapes of the letters and
convert it into editable text.
 Intelligent Robots − Robots are able to perform the tasks given by a human. They have
sensors to detect physical data from the real world such as light, heat, temperature,
movement, sound, bump, and pressure. They have efficient processors, multiple sensors
and huge memory, to exhibit intelligence. In addition, they are capable of learning from
their mistakes and they can adapt to the new environment.

Artificial Intelligence - Issues

AI is developing with such an incredible speed, sometimes it seems magical. There is an opinion
among researchers and developers that AI could grow so immensely strong that it would be
difficult for humans to control.

Humans developed AI systems by introducing into them every possible intelligence they could,
for which the humans themselves now seem threatened.
Threat to Privacy
An AI program that recognizes speech and understands natural language is theoretically capable
of understanding each conversation on e-mails and telephones.

Threat to Human Dignity


AI systems have already started replacing the human beings in few industries. It should not
replace people in the sectors where they are holding dignified positions which are pertaining to
ethics such as nursing, surgeon, judge, police officer, etc.

Threat to Safety
The self-improving AI systems can become so mighty than humans that could be very difficult to
stop from achieving their goals, which may lead to unintended consequences.

Artificial Intelligence (AI) Technique

Artificial intelligence (AI) is both a tool and a fundamental shift in intelligence used by and for
humans. What is this paradigm composed of? Is it evolving well in all aspects of human
intelligence? Let us explore. 

Artificial intelligence (AI) is getting closer and closer to the heights and depths of human
intelligence. That’s what some of us want. That’s what we smell in John McCarthy’s words of
AI’s description too. “The science and engineering of making intelligent machines, especially
intelligent computer programs.” And all this intelligence comes from building agents that act
rationally. That is where we can define the AI technique as a composite of three areas. It is a type
of method built on knowledge, which organizes and uses this knowledge and is also aware of its
complexity.

 Search in artificial intelligence (AI)


 Knowledge representation in artificial intelligence (AI)
 Abstraction in artificial intelligence (AI)  

Let’s break this down one by one.

Search in artificial intelligence (AI)

Artificial intelligence (AI) agents essentially perform some kind of search algorithm in the
background to complete their expected tasks. That’s why search is a major building block for any
artificial intelligence (AI) solution. 
Any artificial intelligence (AI) has a set of states, a start state from where the search begins, and
a goal state. By the use of search algorithms, the solution reaches from the start state to the goal
state.

This is done through various approaches.

 Blind search
 Uninformed and informed search
 Depth first search
 Breadth first search
 Uniform cost search
 Search heuristics 

Knowledge representation in artificial intelligence (AI)

Any artificial intelligence (AI) agent has to work on some input. This work can happen only
when there is some knowledge about the input or about its handling. Artificial intelligence (AI),
hence, has to be strong in understanding, reasoning, and interpreting knowledge. This is done by
the representation of knowledge. It is where the beliefs, intentions, and judgments of an
intelligent agent are expressed by reasoning. This is the place for modeling intelligent behavior
for an agent.

Here, the representation of information from the real world happens for a computer to understand
and leverage this knowledge to solve complex real-life problems. This knowledge can be in the
form of the following.

 Objects
 Events
 Performance
 Facts
 Meta-knowledge
 Knowledge-base
 Declarative knowledge
 Structural knowledge 
 Procedural knowledge
 Meta knowledge 
 Heuristic knowledge 
 Perception component
 Learning component
 Reasoning 
 Execution component

All this is woven into many ways through logical, semantic, frame, and production rules- as
ways of knowledge representation.
Abstraction in artificial intelligence (AI)

When we talk of abstraction, we are looking at an arrangement of the complexity of computer


systems. It helps to reduce complexity and achieve a simplified view of various parts and their
interplay with each other.

This is very important considering the significant criticism that AI tools face. The ‘black box’
effect is a big problem because a lot of effective and stellar AI models cannot explain how they
do what they do. This opacity is a massive barrier to gaining confidence and adoption of artificial
intelligence (AI). So several AI techniques span these areas of search, knowledge, and
abstraction. Like the following. 

 Data Mining – where statistics and artificial intelligence are used for the analysis of large data
sets to discover helpful information
 Machine Vision – where the system can use imaging-based automatic inspection and analysis
for guidance, decisions, automatic inspection, process control, etc.
 Machine Learning (ML) – where models learn from experience and evolve their precision and
delivery over a period
 Natural Language Processing or NLP – where machines can understand and respond to text or
voice data
 Robotics – where expert systems can perform tasks like a human.

Artificial Intelligence Characteristics


1. Deep Learning
Deep learning is a machine learning technique that teaches computers to do what comes naturally
to humans, to learn by example. Innumerable developers are leveraging the latest deep learning
innovative technologies to take their business to the new high.

There are large numbers of fields of Artificial Intelligence technology like autonomous vehicles,
computer vision, automatic text generation, and the like, where the scope and use of deep
learning are increasing.

Take an example of Self Driving feature in cars like Tesla(Autopilot), where Deep learning is
a key technology behind enabling them to recognize a stop sign or to distinguish a pedestrian
from a lamppost.

2. Facial Recognition
Artificial Intelligence has made it possible to recognize individual faces using biometric
mapping. This has lead to pathbreaking advancements in surveillance technologies. It compares
the knowledge with a database of known faces to seek out a match.

However, this has also faced a lot of criticism for breach of privacy.
For example, Clearview AI, an American technology company, offers surveillance technology
for law agencies to monitor entire cities with a network of CCTV Cameras exactly assigning
each and every citizen with their Social Credit Score in real-time.

3. Automate Simple and Repetitive Tasks


AI has the ability to execute the same kind of work over and over again without breaking a
sweat. To understand this feature better, let’s take the example of Siri, a voice-enabled assistant
created by Apple Inc. It can handle so many commands in a single day!

From asking to take up notes for a brief, to rescheduling the calendar for a meeting, to guiding us
through the streets with navigation, the assistant has it all covered.

Earlier, all of these activities had to be done manually which used to take up a lot of time and
effort.

The automation would not only lead to increased efficiencies but also result in lower overhead
costs and in some cases a safer work environment.

4. Data Ingestion
With every passing day, the data that we are all producing is growing exponentially, which is
where AI steps in. Instead of manually feeding this data, AI-enabled not just gathers this data
but also analyzes it with the help of its previous experiences.

Data ingestion is that the transportation of knowledge from assorted sources to a data-storage
medium where it are often accessed, used, and analyzed by a corporation.

AI, with the help of neural networks, analyzes a large amount of such data and helps in providing
a logical inference out of it.

5. Chatbots
Chatbots are software to provide a window for solving customer problems’ through either audio
or textual input. Earlier the bots used to respond only to specific commands. If you say the
wrong thing, it didn’t know what you meant.

The bot was only as smart as it was programmed to be. The real change came when these
chatbots were enabled by artificial intelligence.

Now, you don’t have to be ridiculously specific when you are talking to the chatbot. It
understands language, not just commands.
For example, Watson Assistant, an AI-powered assistant, developed by IBM which can run
across various channels like websites, messengers, and apps and requires zero human
intervention once programmed.

There are a lot of companies that have moved on from voice process executives to chatbots to
help customers solve their problems.

The chatbots not only offer services revolving around issues that the customers face but also
provides product suggestions to the users. All this, just because of AI.

6. Quantum Computing
AI is helping solve complex quantum physics problems with the accuracy of supercomputers
with the help of quantum neural networks. This can lead to path-breaking developments in the
near future.

It is an interdisciplinary field that focuses on building quantum algorithms for improving


computational tasks within AI, including sub-fields like machine learning.

The whole concept of quantum-enhanced AI algorithms remains in the conceptual research


domain

For example, A pioneer in this field is Google AI Quantum whose objective is to develop
superconducting qubit processors and quantum-assisted optimization for varied applications.

7. Cloud Computing
Next Artificial Intelligence characteristics is Cloud Computing. With such a huge amount of data
being churned out every day, data storage in a physical form would have been a major problem.

AI capabilities are working within the business cloud computing environment to make
organizations more efficient, strategic, and insight-driven.

However, the advent of Cloud Computing has saved us from such worries.

Microsoft Azure is one of the prominent players in the cloud computing industry. It offers to
deploy your own machine learning models to your data stored in cloud servers without any lock-
in.

Characteristics of AI applications ( YET TO EDIT )

Introduction to LISP programming


Lisp is a programming language that has an overall style that is organized around expressions
and functions. Every Lisp procedure is a function, and when called, it returns a data object as its
value. It is also commonly referred to as “functions” even though they may have side effects.

Lisp is the second-oldest high-level programming language in the world which is invented by
John McCarthy in the year 1958 at the Massachusetts Institute of Technology.

Features of  LISP Programming Language:

1. It is a machine-independent language
2. It uses iterative design methodology and is easily extensible
3. It allows us to create and update the programs and applications dynamically.
4. It provides high-level debugging.
5. It supports object-oriented programming.
6. It supports all kinds of data types like objects, structures, lists, vectors, adjustable arrays, set,
trees,hash-tables, and symbols.
7. It is an expression-based language
8. It can support different decision-making statements like if, when,case, and cond
9. It will also support different iterating statements like do, loop,loopfor, dotimes and dolist.
10. It will support input and output functions
11. By using lisp we can also create our own functions

These are the features of LISP Programming.

Hello World program in LISP:

we can start writing  a string by using the write-line method

Syntax:

(write-line string)

Example:

;this is a comment

(write-line "Hello Geeks")

Output:

Hello Geeks

Naming Conventions:

The naming Conventions mean the way we are declaring variables in a program. It includes the
variable names and syntax formats
Lets us discuss the conventions

 A variable can contain  any number of alphanumeric characters other than whitespace, open
and  closing parentheses

Example:

Acceptable – hello,saisravan, etc

Not Acceptable – hell()0,sat{ sravab{,,,,,,,,etc

 A variable can not contain double and single quotes, backslash, comma, colon, semicolon, and
vertical bar.

Example:

Acceptable – hello,saisravan, etc

Not Acceptable – hell””)0,sat//*& sra//>vab{,,,,,,,,etc

 A variable can not start with a digit but. it can contain any number of digits

Example:

Acceptable – hello88Geeks, r56lisp, ,,,,,etc

Not Acceptable – 40geeks,4klll,….etc

Example Code: For acceptable names

;acceptable naming conventions

(write-line "hello")

 (terpri)

;acceptable naming conventions

(write-line "hello99")

(terpri)

;acceptable naming conventions

(write-line "hello geeks")

(terpri)
 

;acceptable naming conventions

(write-line "hello_Geek")

(terpri)

;acceptable naming conventions

(write-line "hello123")

Output:

hello
hello99
hello geeks
hello_Geek
hello123

Functions in LISP

A function is a set of statements that takes some input, performs some tasks, and produces the
result. Through functions, we can split up a huge task into many smaller functions. They also
help in avoiding the repetition of code as we can call the same function for different inputs.

Defining Functions in LISP: 

Functions in LISP are defined using the DEFUN macro. The basic syntax looks like this : 

(defun function-name (parameters)


"Documentation string"
body-of-function
)

 Name of Function: You can use any kind of symbol as a function name, but usually function
names includes only characters and hyphens. In LISP instead of using underscore in naming,
hyphens are considered as naming conventions. For example, we write calc-average instead of
calc_average or calcAverage.
 Parameters: These are the variables that are used to retain the arguments that are passed to
the function when it is called. These parameters are optional, if a function doesn’t have any
parameters, then that list is empty written as ( ) 
 Documentation String: It is a string literal that is used to describes what a particular function is
intended to do.
 Body of function: The function body consists of LISP expressions which are evaluated in order
when the function is called. Usually, the value of the last expression is returned as the value of
the function, but through the help of RETURN-FORM which is a special operator, we can return
the value of the function from anywhere in it.
Example:

1. Let’s create a function named hello-world that doesn’t take any parameters and returns a hello
world string.

(defun hello-world () 

  (format t "Hello, World!")

(hello-world)

Output:

Hello, World!

2. Function to add two integers

Here we have created a function named add-two-number which takes two arguments n1 and n2.
A Documentation string is used to describe the work done by this function and whatever the
value is return by calling the + eventually becomes the return value of add-two-number.

(defun add-two-number (n1 n2)

  "Adds two numbers"

  (+ n1 n2)

(write(add-two-number 10 20))

Output:

30

3. Now let’s create a simple function that takes an optional string argument and return the
Welcome string : 

In the function welcome-to-gfg,  we have one optional parameter name. To define any optional
parameter add the symbol: &optional before the name of the parameter which is optional.
We have set its default value to Sandeep, So if the user calls the welcome-to-gfg function
without any arguments it prints “Welcome “Sandeep” to Geeks for geeks!” or if any argument is
passed while calling the function it will return the string which contains the argument value
passed while calling the function.
(terpri) is used to print a new line
(defun welcome-to-gfg (&optional (name "Sandeep"))

  (format t "Welcome ~S to Geeks for geeks!" name)

(welcome-to-gfg)

(terpri)

(welcome-to-gfg "UserName")

Output: 

Welcome "Sandeep" to Geeks for geeks!


Welcome "UserName" to Geeks for geeks!

LISP is a list processing programming language. It is widely used in the manipulation of data
strings. It provides an input and output library. LISP provides a macro system and provides well
control structures for the manipulation of data.

LISP Math Function:

 floor:  floor returns the nearest smallest number.


 ceiling: ceiling return the nearest largest number.
 round: rounds the argument or quotient of the arguments to the nearest integer.
 mod: Returns the remainder in a division operation.
 complex:  Returns a number whose real part is real part and whose imaginary part is imaginary
part

Attributes Used:

 setq: It is used to set the value to a variable.


 printc: It is used for print output.
 terpri: It is used to produce a new line. 
 write: It is used for writing.

Example 1:

; Normal Arithmetic calculation in

; LISP(Addition, Subtraction, Multiplication, division)

;set value 1 to 190

; set value 2 to 78

(setq val1 190)


(setq val2 78)

;addition operation

(princ "addition")

(print (+ val1 val2))

;subtraction operation

(princ "subtraction")

(print (- val1 val2))

;multiplication operation

(princ "multiplication")

(print (* val1 val2))

;division operation

(princ "division")

(print (/ val1 val2))

;modulus operation

(princ "modulus")

(print (MOD val1 val2))

;increment a by 10

(princ "increment by 10")

(print (incf val1 val2))

;decrement b by 20

(princ "increment by 20")

(print (decf val1 val2))

Output:
 

Example 2:

;Predefined Arithmetic data type in LISP

(princ "floor:  ")

(write (floor 45.78))

(terpri)

(princ "ceiling:   ")

(write (ceiling 34.34))

(terpri)

(princ "round:   ")

(write (round 34.3))

(terpri)

(princ "ffloor:   ")

(write (ffloor 34.43))

(terpri)

(princ "fceiling:   ")

(write (fceiling 34.12))

(terpri)

(princ "fround:   ")

(write (fround 34.75))

(terpri)
(princ "mod:   ")

(write (mod 34 5))

(terpri)

(princ "complex:   ")

(setq c (complex 6 7))

(write c)

(terpri)

Output:

Lists in LISP

Lists in common LISP is simply a single Linked list. In LISP, Lists are designed as a chain of
records. While talking about record structures in LISP, the concept of Cons is vital. Cons in
LISP is a record structure with 2  primary components. A cons function takes in 2 arguments and
returns a new cons cell with car and dir.

1. car: It is used to access the first value in a cons function.


2. cdr: It is used to access the second value in the cons function.

Note: If the second value is not nil or is just another cons cell, then the values are printed as a
dotted pair enclosed by parentheses.

Example:

; cons with 2 string object reference

(write (cons 'Geeksforgeeks 'Is_Best))

(terpri)

 
; cons with 1 nil value as argument

(write (cons 999 nil))

(terpri)

;cons with another cons as argument

(write (cons 'A (cons 'B nil)))

(terpri)

;cons with otyhen nested cons as argument

(write (cons 'A (cons 'B (cons 'C nil))))

Output:

(GEEKSFORGEEKS . IS_BEST)
(999)
(A B)
(A B C)

Lists in LISP:

The list function in LISP can be used to create a list in LISP.

Syntax:

write( list value1 value 2 ...)

Note: The list function can take any no. of arguments.

Example: 

(write (list 1 2))

(terpri)

(write (list 'g 'e 'e'k's))

(terpri)

(write (list 'Geeksforgeeks' nil))

(terpri)

;list with a cons as an argument

(write (list 3 4 'geeks (car '(G . F)) (* 99  +78)))


(terpri)

; list with another list as an argument

(write (list (list 'Geeksforgeeks 'is) (list 'the 'best 'resource 'for 'DSA)))

Output:

(1 2)
(G E E K S)
(GEEKSFORGEEKS NIL)
(3 4 GEEKS G 7722)
((GEEKSFORGEEKS IS) (THE BEST RESOURCE FOR DSA))

Accessing Elements of a LIST:

The combination of car and cdr functions in common LISP can be used to extract elements from
a list. The combination of carr and cdr can be abbreviated as cadadr/caar/cadr and so on.

Example:

; here we will extract the string Best

(write (cadadr '(Geeksforgeeks (is best) (for Data Structures))))

(terpri)

; here we will extract the string Geeks

(write (caar (list (list 'Geeks 'for) 'geeks)))  

(terpri)

; here we will use the abbv. cadr

(write (cadr (list (list 'A 'B) (list 'C'D))))

Output:

BEST
GEEKS
(C D)

List Manipulation in LISP

In this article, we will discuss List manipulation in LISP. The list is a data structure that can store
elements of multiple data type
we can create a list by using the list function

Syntax:

(list element1 element2 .................. element n)

List manipulating functions are used to manipulate and return the list of elements

1. car() Function:

This function is used to display the first element in the list

Syntax:

(car '(element1 element2 ........... element n))

Example:

;list of integer elements

(write (car '(1 2 3 4 5)))

(terpri)

;list of characters

(write (car '(a b)))

(terpri)

Output:

1
A

2. cdr() Function:

This function is used to display the list of all elements excluding the first element 

Syntax:

(cdr '(element1 element2 ........... element n))

Example:

;list of integer elements

(write (cdr '(1 2 3 4 5)))


(terpri)

;list of characters

(write (cdr '(a b)))

(terpri)

Output:

(2 3 4 5)
(B)

3.cons() FUnction:

This function will take two items. one is a value and another is the list. This will insert the value
into first place in the list and returns the new list

Syntax:

(cons 'value '(list_of_elements)))

where,

 value is the element to be inserted


 list_of_elements is the list of elements

Example:

;list of integer elements

;insert 100

(write (cons '100 '(1 2 3 4 5)))

(terpri)

;list of characters

;insert a

(write (cons 'a '(b c d e f)))

(terpri)

Output:

(100 1 2 3 4 5)
(A B C D E F)
4. list() Function:

This function will take multiple lists and display it

Syntax:

(list 'list1 'list2 ........ 'listn)

Example:

;two lists and one variable

(write (list '100 '(1 2 3 4 5) '(g e e k s)))

(terpri)

Output:

(100 (1 2 3 4 5) (G E E K S))

5. append() Function:

This function will append the two or multiple lists.

Syntax:

(append'list1 'list2 ........ 'listn)

Example:

;consider two lists and append

(write (append  '(1 2 3 4 5) '(g e e k s)))

(terpri)

;consider three lists and append

(write (append '(10 20) '(20 30 45) '(a s d)))

(terpri)

Output:

(1 2 3 4 5 G E E K S)
(10 20 20 30 45 A S D)
6. last() Function:

This function returns the list that contains the last element in the list

Syntax:

(last 'list)

Example:

;consider a list and get last element

(write (last  '(1 2 3 4 5) ))

(terpri)

;consider a list and get last element

(write (last '(10 20 ( g e e k s))))

(terpri)

Output:

(5)
((G E E K S))

7. member() Function:

This function is used to return the list based on members given.

It will take two arguments:

1. The first argument will be the value.


2. The second argument will be the list.

If the value is present in the list, then it will return the list

Otherwise, NIL is returned.

Syntax:

(member 'value 'list )

Example:

;consider a list with 1 as member 


(write (member  '1 '(1 2 3 4 5) ))

(terpri)

;consider a list with 10 as member 

(write (member  '10 '(1 2 3 4 5) ))

(terpri)

Output:

(1 2 3 4 5)
NIL

8. reverse() Function:

This function reverses the list and returns the reversed list

Syntax:

(reverse 'list)

Example:

;consider a list and reverse

(write (reverse  '(1 2 3 4 5) ))

(terpri)

;consider a list nnd reverse

(write (reverse  '(g e e k s) ))

(terpri)

Output:

(5 4 3 2 1)
(S K E E G)

Predicates in LISP

In this article, we will discuss predicates. Predicates are similar to functions that will be used to
test their arguments for conditions. They will return NIL if the conditions are not met, if the
conditions are met, they will return T.
Types of predicates:
Below is a list of major Predicates with syntax and examples.

1. atom:

This predicate will return t if the argument is an atom otherwise it will return nil.

Syntax:

(atom 'element)

Example:

;check atom or not

(write (atom 'geeks))

(terpri)

Output:

2. equal:

This predicate will check the given two arguments are equal or not, if equal it returns T
otherwise nil.

Syntax:

(equal 'element1 'element2)

Example:

;check equal or not

(write (equal 'geeks 'forgeeks))

(terpri)

;check equal or not

(write (equal 'python 'python))

(terpri)
Output:

NIL
T

3. eq:

This predicate will check will two arguments are identical in the case of sharing the same
memory

It will return t if they are identical, otherwise nil

Syntax:

(eq 'element1 'element2)

Example:

;check equal or not

(write (eq 'geeks 'forgeeks))

(terpri)

;check equal or not

(write (eq 45 45))

(terpri)

Output:

NIL
T

4. evenp:

This predicate will check the given number is even or not. It will return t if the number is even
otherwise nil

Syntax:

(evenp element)

Example:

;check even or not


(write (evenp 31))

(terpri)

;check even or not

(write (evenp 20))

(terpri)

Output:

NIL
T

5. oddp:

This predicate will check the given number is odd or not.

It will return t if the number is odd otherwise nil

Syntax:

(oddp element)

Example:

;check odd or not

(write (oddp 31))

(terpri)

;check odd or not

(write (oddp 20))

(terpri)

Output:

T
NIL

6. zerop:

This predicate will check the given number is zero or not

it will return t if the number is zero otherwise nil


Syntax:

(zerop element)

Example:

;check zero or not

(write (zerop 0))

(terpri)

;check zero or not

(write (zerop 20))

(terpri)

Output:

T
NIL

7. null:

This predicate will check the given element is nil or not, it returns T when the given element in
nil otherwise NIL

Syntax:

(null element)

Example:

;check null or not

(write (null 0))

(terpri)

;check null or not

(write (null nil))

(terpri)

Output:

NIL
T

8. listp:

It will return t if the given element is in a list otherwise nil

Syntax:

(listp element)

Example:

;check list or not

(write (listp 0))

(terpri)

;check list or not

(write (listp  '(g e e k s)))

(terpri)

Output:

NIL
T

9. numberp:

This predicate will return if the given argument is number otherwise nil

Syntax:

(numberp element)

Example:

;check number or not

(write (numberp 67  ))

(terpri)

;check number or not

(write (numberp  '(g e e k s)))


(terpri)

Output:

T
NIL

10. integerp:

This predicate will return t if it is an integer otherwise nil will return

Syntax:

(integerp element)

Example:

;check integer or not

(write (integerp 67  ))

(terpri)

;check integer or not

(write (integerp  '(g e e k s)))

(terpri)

Output:

T
NIL

11. rationalp:

This predicate will return t if the argument  is a rational number otherwise nil will return

Syntax:

(rationalp element)

Example:

;check rational or not

(write (rationalp 67 ))
(terpri)

  

;check rational or not

(write (rationalp  '(g e e k s)))

(terpri)

Output:

T
NIL

12. complex:

This predicate will return t if the argument  is a complex number otherwise nil will return

Syntax:

(complexp element)

Example:

;check complex or not

(write (complexp #c( 10 30) ))

(terpri)

;check complex or not

(write (rationalp  '(g e e k s)))

(terpri)

Output:

T
NIL

13. characterp:

This predicate will return t if the argument  is a character otherwise nil will return

Syntax:

(characterp element)
Example:

;check character or not

(write (characterp 'h ))

(terpri)

;check character or not

(write (characterp  '(g e e k s)))

(terpri)

Output:

NIL
NIL

14. floatp:

This predicate will return t if the argument  is an floating number otherwise nil will return

Syntax:

(floatp element)

Example:

;check float or not

(write (floatp  56.78 ))

(terpri)

;check float or not

(write (floatp  67))

(terpri)

Output:

T
NIL

15. realp:

This predicate will check the given number is real or not. It will return t if it is real otherwise nil
Syntax:

(realp element)

Example:

;check real or not

(write (realp  56.78 ))

(terpri)

;check real or not

(write (realp  67))

(terpri)

Output:

T
T

16. stringp:

This predicate will check the given argument is a string or not. It will return t if it is string
otherwise nil

Syntax:

(stringp element)

Example:

;check string or not

(write (stringp  "heelo geeks" ))

(terpri)

;check string or not

(write (stringp  67))

(terpri)

Output:

T
NIL

17. arrayp:

This predicate will return t if the argument is an array otherwise nil.

Syntax:

(arrayp element)

Example:

;create an array

(write (setf array1 (make-array '(10))))

(terpri)

;check array or not

(write (arrayp  array1))

(terpri)

;check array or not

(write (arrayp  90))

(terpri)

Output:

#(NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL)
T
NIL

Decision Making in LISP

Decision making is used to specify the condition to evaluate an expression in LISP.

There are 4 types of decision-making statements in LISP. They are

 if
 cond
 when
 case
if Statement

The if is a decision-making statement used to check whether the condition is right or wrong. The
if the condition is right, then it will go inside the if block and execute the statements under if
block. Otherwise, the statements are not executed.

Syntax:

(if (condition) then (statement 1).....(statement n))

Here, then is an optional keyword used inside the if statement.

Example 1: LISP Program to check conditions with operators

;define value to 100

(setq val1 100)

;check the number is equal to 100

(if (= val1 100)

   (format t "equal to 100"))

(terpri)

;check the number is greater than to 50

(if (> val1 50)

   (format t "greater than 50"))

(terpri)

;check the number is less than to 150

(if (< val1 150)

   (format t "less than 150"))

Output:

equal to 100
greater than 50
less than 150

Example 2:

;define value to 230


(setq val1 230)

;check the number is equal to 100

(if (= val1 100)

   (format t "equal to 100"))

(terpri)

;check the number is greater than to 50

(if (> val1 50)

   (format t "greater than 50"))

(terpri)

;check the number is less than to 150

(if (< val1 250)

   (format t "less than 250"))

Output:

greater than 50
less than 250

cond Statement

The cond is a decision-making statement used to make n number of test conditions. It will check
all the conditions.

Syntax:

(cond (condition1 statements)


(condition2 statements)
(condition3 statements)
...
(conditionn statements)
)

Here,

 The conditions specify different conditions – if condition1 is not satisfied, then it goes for the
next condition  IE condition until the last condition.
 The statements specify the work done based on the condition.

Note: It will execute only one statement.


Example 1: LISP program to check whether a number is greater than 200 or not.

;set value1 to 500

(setq val1 500)

;check whether the val1 is greater than 200

(cond ((> val1 200)

   (format t "Greater than 200"))

   (t (format t "Less than 200")))

Output:

Greater than 200

Example 2: Demo with operators

;set value1 to 500

(setq val1 500)

;check whether the val1 is greater  than 200

(cond ((> val1 200)

   (format t "Greater than 200"))

   (t (format t "Not")))

 (terpri)

;check whether the val1 is equal to 500

(cond ((= val1 500)

   (format t "equal to 500"))

   (t (format t "Not")))

 (terpri)

;check whether the val1 is equal to 600

(cond ((= val1 600)

   (format t "equal to 500"))

   (t (format t "Not")))


 (terpri)

 ;check whether the val1 is greater than or equal to 400

(cond ((>= val1 400)

   (format t "greater than or equal to 400"))

   (t (format t "Not")))

 (terpri)

;check whether the val1 is less than or equal to 600

(cond ((<= val1 600)

   (format t "less than or equal to 600"))

   (t (format t "Not")))

 Output:

Greater than 200


equal to 500
Not
greater than or equal to 400
less than or equal to 600

when Statement

 The when is a decision-making statement used to specify the decisions. It is similar to


conditional statements.

Syntax: 

(when (condition) (statements) )

where, 

1. condition is a test statement used to test


2. statements are the actions that will depend on the condition

Example 1: LISP Program to check the number is equal to 50 or not

;set number to 50

(setq number 50)

 
;condition check the given number is equal to 50

(when (= number 50)

;statement

  (format t "Equal to 50")

   )

Output:

Equal to 50

Example 2: LISP Program to check the given number with comparison operators

;set number to 50

(setq number 50)

;condition check the given number is equal to 50

(when (= number 50)

;statement

  (format t "Equal to 50")

   )

(terpri)

;set number to 150

(setq number 150)

;condition check the given number is greater than or equal to 50

(when (>= number 50)

;statement

  (format t "greater than or Equal to 50")

   )

(terpri) 

   ;set number to 10

(setq number 10)


 

;condition check the given number is less than or equal to 50

(when (<= number 50)

;statement

  (format t "less than or Equal to 50")

   )

Output:

Equal to 50
greater than or Equal to 50
less than or Equal to 50

case Statement

This is used to check multiple test conditions at a time, unlike cond, if and when it allows
multiple conditions.

Syntax:

(case (key_value)
((key1) (statement 1 .............. statement n) )
((key2) (statement 1 .............. statement n) )
................
((keyn) (statement 1 .............. statement n) )

here,

1. key_value is the numeric value taken a input


2. keys are the different conditions to test particular condition specified  in keys

Example: LISP Program to get the particular number when the number is given

;define value to 2

(setq val1 2)

;define 5 cases from 1 to 5

(case val1

(1 (format t "you selected number 1"))

(2 (format t "you selected number 2"))


(3 (format t "you selected number 3"))

(4 (format t "you selected number 4"))

(5 (format t "you selected number 5"))

Output:

you selected number 2

Example: LISP Program to perform an arithmetic operation when a particular key is chosen

;define value1 to 10

(setq val1 10)

;define value2 to 20

(setq val2 20)

;set input to 1

(setq input 1)

;define 4 cases to perform each arithmetic operation

(case input

;condition to perform addition

(1 (print (+ val1 val2)))

;condition to perform subtraction

(2 (print (- val1 val2)))

;condition to perform multiplication

(3 (print (* val1 val2)))

;condition to perform division

(4 (print (/ val1 val2)))

Output:

30
Set input to 3

;define value1 to 10

(setq val1 10)

;define value2 to 20

(setq val2 20)

;set input to 3

(setq input 3)

;define 4 cases to perform each arithmetic operation

(case input

;condition to perform addition

(1 (print (+ val1 val2)))

;condition to perform subtraction

(2 (print (- val1 val2)))

;condition to perform multiplication

(3 (print (* val1 val2)))

;condition to perform division

(4 (print (/ val1 val2)))

Output:

200

Input & Output in LISP

Lisp provides a huge set of facilities for performing input/output. All the input/output operations
are performed on streams of several kinds. While reading and writing binary data is possible, the
majority of Common Lisp input/output methods read or write characters. For reading and writing
individual characters or lines of data, there are straightforward primitives. However, reading and
writing written representations of any arbitrary Lisp objects is the most helpful input/output
operation.

Lisp Objects:
Lisp objects are typically intricate data structures rather than text strings. They differ from text
strings in terms of attributes because of how they are internally represented. However, Lisp
offers a representation of the majority of objects in the form of written text, known as the printed
representation, which is used for I/O facilities. This makes it possible to access and discuss Lisp
objects.

The characters of a Lisp object’s printed representation are transmitted to a stream via functions
like print. The (Lisp) printer is a group of functions that accomplishes this. The (Lisp) reader is a
group of routines that performs the read function, which accepts characters from a stream,
interprets them as a printed representation of a Lisp object, creates that object, and returns it.

Input Functions:
The input functions are split into two categories: those that work with character streams and
those that work with binary streams.

Input from Character Streams:

There are many optional arguments in character input functions called input-stream, eof-error-p,
and eof-value. The input-stream argument is the stream from which to collect input; if not
specified or nil it defaults to the value of the special variable ‘standard-input’. The eof-error-p
parameter controls what happens if the input is from a file and the end of the file is reached. If
eof-error-p is true which is the default, an error will be signaled at end of the file. If it is false,
then no error is encountered, and instead, the function returns eof-value.

read &optional input-stream eof-error-p eof-value recursive-p 

 It constructs a corresponding Lisp object based on the written representation of a Lisp object
read from the input stream and then returns the object.

read-line &optional input-stream eof-error-p eof-value recursive-p 

 read-line inserts a line of text that has been separated by a newline. The line is given back as a
character string (without the newline character). This function is typically used to obtain a line of
user input. A flag that is true if the end-of-file terminated the (non-empty) line or false if the line
was terminated properly is the second value that is returned.

read-char &optional input-stream eof-error-p eof-value recursive-p 

 One character is taken from the input stream and returned as a character object by read-char.

unread-char character &optional input-stream 

 The character is moved to the front of the input stream by unread-char. The character must
match the one that was just read from the input stream. When a character is next read from the
input stream, it will be the specified character followed by the previous contents of the input
stream because the input stream “backs up” over this character. Unread-char returns back nil.

read-preserving-whitespace &optional in-stream eof-error-p eof-value recursive-p

 When it is necessary to know precisely which character ended the extended token, the function
read-preserving-whitespace is offered.

read-delimited-list char &optional input-stream recursive-p

 This reads objects from the stream until the following character is a char (while disregarding
whitespace and comments). It returns a list of the read items.

peek-char &optional peek-type input-stream eof-error-p eof-value recursive-p 

 The peek-type, which has a default value of nil, determines what peek-char performs. Without
actually deleting the character from the input stream, peek-char returns the next character to
be read from the input stream when the peek-type is nil. The character will remain when input
from the input stream is performed again later. It appears as though read-char and unread-char
were called back-to-back.

listen &optional input-stream 

 When a character is instantly available from the input stream, the predicate listen is true;
otherwise, it is false. This is especially helpful when the stream gets its characters from a
keyboard or other interactive device.

read-char-no-hang &optional input-stream eof-error-p eof-value recursive-p 

 It is similar to read-char, but instead of waiting for a character if it doesn’t receive one, it returns
nil right away.

clear-input &optional input-stream

 By doing this, the input-related stream’s buffered input is cleared. When an asynchronous error
has occurred, it is most useful for clearing type-ahead from keyboards. If the stream in question
doesn’t make sense for this operation, clear-input has no effect. Clearing input yields nil.

read-from-string string &optional eof-error-p eof-value &key :start :end :preserve-whitespace

 It generates a LISP object out of the string’s characters one at a time, then returns the object.
Additionally, it returns the length of the string (or length + 1), or the index of the first character
in the string that was not read.

parse-integer string &key :start :end :radix :junk-allowed 


 It looks at the portion of the string that is start and end-delimited (default to the beginning and
end of the string). Whitespace characters are skipped over before an attempt is made to parse
an integer.

Example :

;LISP- Input 

(with-input-from-string (stream "Geeks for Geeks welcomes you!")

   (print (read-char stream))

   (print (read-char stream))

   (print (read-char stream))

   (print (read-char stream))

   (print (read-char stream))

   (print (read-char stream))

   (print (read-char stream))

   (print (read-char stream))

   (print (read-char stream))

   (print (read-char stream))

   (print (peek-char nil stream nil 'the-end))

   (values)

Output :
 

Input from Binary Streams:

read-byte binary-input-stream &optional eof-error-p eof-value 

 read-byte extracts one byte from the binary input stream and returns it as an integer.

Reading Input from Keyboard:

The read function in Common Lisp allows for keyboard input. It may not take any parameter.
Characters are read from an input stream and parsed into representations of Lisp objects.

Syntax:

(setq varname (read))

This statement will take input from the keyboard and store it in the variable.

Example:

; Lisp program to demonstrate 

; use of read function

; Program inputs value of radius from

; keyboard and calculates the perimeter of circle

  

(defun PerimOfCircle()

(terpri)

(princ "Enter Radius: ")

(setq radius (read))

(setq perimeter (* 2 3.1416 radius))

(princ "Perimeter: ")

(write perimeter))

(PerimOfCircle)

Output:
 

Output Functions:
The output functions are split into two categories: those that work with character streams and
those that work with binary streams. Due to its extreme complexity, the function format—which
operates on streams of characters—is discussed in a section separate from that of the other
character-output functions.

Output to Character Streams:

Each of these routines accepts an optional argument called output-stream that specifies where the
output should be sent. Output-stream defaults to the value of the variable “standard-output” if
unspecified or nil. The value of the variable “terminal-io” is used if the value is t.

write object &key :stream :escape :radix :base :circle :pretty :level :length :case :gensym :array

write object
&key :stream :escape :radix :base :circle :pretty :level :length :case :gensym :array :readably :rig
ht-margin :miser-width :lines :pprint-dispatch

 The output stream designated by: stream, which by default has the value of “standard-output,”
receives the printed version of the object.

prin1 object &optional output-stream


print object &optional output-stream
pprint object &optional output-stream
princ object &optional output-stream

 prin1 sends an object’s printed representation to the output stream. When necessary, escape
characters are utilized.
 Print is identical to prin1, with the exception that a newline and a space is used to separate the
printed representation of an item. print outputs the object.
 In order to provide “beautiful” output, the object is printed with the “print-pretty” flag set to
non-nil when using pprint rather than print. pprint gives no results.
 Except for the absence of escape characters in the output, princ is identical to prin1. It gives the
object back as the value.

write-to-string object
&key :escape :radix :base :circle :pretty :level :length :case :gensym :array
prin1-to-string object
princ-to-string object

 The object is effectively printed, and a string is created from the output characters and
returned.

write-char character &optional output-stream

 write-char writes the character to output-stream and returns the character.

write-string string & optional output-stream & key :start :end

 The write-string command output streams the characters of the supplied string substring. A
substring of a string is delimited by the: start and: end parameters in a typical way.

terpri &optional output-stream


fresh-line &optional output-stream

 A newline is output to the output stream by the function terpri. However, terpri always returns
nil, unlike (write-char #Newline output-stream), which is equivalent in effect.
 Similar to terpri, fresh-line only outputs a newline if the stream is not already at the beginning of
a line.

finish-output &optional output-stream


force-output &optional output-stream
clear-output &optional output-stream

 The function finish-output tries to ensure that all output sent to the output-stream has reached
its destination, and only then returns nil.
 The function force-output initiates the clearing of any internal buffers but returns nil without
waiting for completion or acknowledgment.
 The function clear-output tries to abort any outstanding output operation in progress in order to
allow as small output as possible to continue to the destination.

Example :

; Lisp program to show output functions

; Program to double a number

  
  

(defun DoubledNumber()

   (terpri)

   (princ "Enter the Number : ")

   (setq n1 (read))

   (setq double (* 2.0 n1))

   (princ "The number is: ")

   (write n1)

   (terpri)

   (princ "The doubled number is: ")

   (write double)

(DoubledNumber)

Output :

Output to Binary Streams:

write-byte integer binary-output-stream

 write-byte outputs an integer value of one byte. If the integer does not fit the description
provided as the ‘element-type’ argument to open when the stream was established, it is an
error. The result is an integer value.
Formatted Output:

The function format is highly helpful for creating well-formatted text, attractive messages, and
other things. A stream or a string can be produced by format.

Syntax:

format destination control-string &rest arguments

The standard output is the syntax’s destination, while the control-string variable holds the
characters that will be output along with the printing instruction.

With the exception of the tilde (~), which begins a directive, the format outputs the characters of
the control string. It is specified by the character following the tilde, which may be followed by
prefix parameters and modifiers. A tilde (~), optional prefix parameters separated by commas, an
optional colon (:) and at-sign (@) modifiers, and a single character designating the type of
directive this is make up a format directive.

Typically, the prefix parameters are integers with optionally signed decimal notation.

The following table tabulates some of the commonly used directives with their descriptions:

Directive Description

~A followed by ASCII arguments.

~S followed by S-expressions.

~B For binary arguments.

~C For character arguments.

~D For decimal arguments.

~E Exponential floating-point arguments.

~F For Fixed-format floating-point arguments.

~O For octal arguments.

~X For hexadecimal arguments.

~$ Dollar and floating point arguments.

~% A new line is printed.

~* The next argument is ignored.


Directive Description

~? Indirection. The next argument must be a string, and the one after it a list.

~T Tabulate. This spaces over to a given column.

Example :

;Lisp program to show format function

(defun PerimOfCircle()

   (terpri)

   (princ "Enter Radius: ")

   (setq radius (read))

   (setq Perimeter (* 2 3.1416 radius))

   (format t "Radius: = ~F~% Perimeter = ~F" radius Perimeter)

(PerimOfCircle)

Output :

Loops in LISP

Loops allow executing a set of instructions repeatedly while some condition is true. LISP
provides the following types of loops:
1. dotimes loop:

The dotimes loop allows executing instructions for a fixed number of times.
Syntax: 

(dotimes( variableName numberOfIterations ) (


expressions
))

Where,

 variableName => Name of the variable, this can be used to get current iteration number
 numberOfIterations => Total number of iterations
 expressions => Statements to be executed in each iteration

Example:

(dotimes (a 4)

  (print a))

(write-line "")

Output:

You can also return from the loop if a certain condition is met

(dotimes (i 7)

   (if (> i 5)

       (return)

       (print i))

    )

(write-line "")
Here, the loop is set to iterate 7 times, however, when the value becomes more than 5, the loop
stops because the condition is met. 
Output:

2.  loop:

The loop construct allows executing some statement(s) repeatedly until it finds a return
statement.

Syntax: 

( loop
(expressions)
( when (condition) (return returnValue))
)

Where,

 expressions => Statements to be executed in each iteration


 condition => Condition that specifies when to exit loop
 returnValue => Value to be returned

Example:

(defvar n 3)

(loop

    (print n)

    (setq n (+ n 1))

    (when (> n 6) (return n))

(write-line "")

Here, n is printed and incremented until it becomes greater than 6.


Output:
3. loop for:

The loop for construct is similar to the for-loops in popular languages like java, c++, etc. It can
also be used to traverse lists and other data structures.

Syntax:

( loop for variableName from startValue to endValue by changeValue do


(expressions)
)

Where,

 variableName => Name of the variable, this can be used to get the value of variable in current
iteration. 
 startValue => Initial value of variable
 endValue => End value of variable (after last iteration)
 changeValue => Specifies by how much to increment or decrement value after every iteration
 expressions => Statements to be executed in each iteration

Example:

; initialize x=12, execute instructions, 

; increment it by 3 and perform iteration until it is less than 25

(loop for x from 12 to 25 by 3 do

    (print x)

(write-line "")

Output:
4. do:

The do construct allows a structured form of iteration.


Syntax:

(do ((variable_1 value_1 updated-value_1)


(variable_2 value_2 updated-value_2)
(variable_3 value_3 updated-value_3)
...)
(test return_value)
(s-expressions)
)

Where,

 variable_1 => First variable


 value_1 => Initial Value for first variable
 updated-value_1 => Specifies how to update variable_1 after each iteration.
 variable_2 => Second variable
 value_2 => Initial Value for second variable
 updated-value_2 => Specifies how to update variable_2 after each iteration. … similar till
variable_n
 test => Condition that specifies when to stop the loop
 return value => Value that is returned at the end of iteration
 expressions => Other statements to be executed in every iteration

The initial values of each variable are evaluated and bound to the respective variable. The
updated value in every clause is with respect to an optional update statement which indicates
how to update variables in each iteration.
The test is performed on each iteration and if the test expression results in a non-null or true
value, the returned value is evaluated and returned.
If the last optional s-expression(s) are specified, they’re executed on every iteration while test
expression results are true.
Example:

(do ((a 0 (+ 2 a))


   (b 20 ( - b 2)))

   ((= a b)(- a b))

   (format t "~% a = ~d  b = ~d" a b)

(write-line "")

Output:

5. dolist:

The dolist construct provides an easy way to traverse lists.

Syntax:

(dolist (listItemVariable list)


(expressions)
)

Where,

 listItemVariable => Holds value of each list item during every iteration
 list => List to traverse
 expressions => Statements to be executed in every iteration

Example:

(defvar nums `(9 5 2 3))

(dolist (item nums)

  (print item)

)
(write-line "")

Output:

Property Lists in LISP

In Lisp, every symbol has a property list (plist). When a symbol is created initially its property
list is empty. A property list consists of entries where every entry consists of a key called an
indicator and a value called a property . There are no duplicates among the indicators. In contrast
to association lists the operations for adding and removing plist entries alter the plist rather than
creating a new one.

               Function                    Syntax Usage


get searched the plist for an indicator
equivalent to indicator. If the found
get symbol indicator
get function value is returned or else the default is
&optional default
returned. If the default is not specified
nil is returned.
 setf((get function) setf is used with getting to create a
setf function
property/value) new property value pair.
symbol-plist allows you to see all the
symbol-plist (symbol-plist  symbol)
properties of a symbol
remprop function is used to remove
remprop remprop symbol indicator the property equivalent to the
indicator.
getf searches the property list stored in
place for an indicator equivalent to an
indicator. If one is found, then the
getf place indicator
getf corresponding value is returned;
&optional default
otherwise, the default is returned. If
the default is not specified, then nil is
used for default.
remf removes the property equivalent
remf remf place indicator to the given indicator from the given
place.
Example:

(setf (get 'aastha 'age ) 20)


;using setf (which understands get as a place description) 
;to create indicator age with value 20 of symbol aastha.
  
(setf (get 'aastha 'occupation ) 'doctor)
;using setf (which understands get as a place description) 
;to create indicator occupation with value doctor of symbol aastha.
  
(setf (get 'aastha 'fav-book ) 'harrypotter)
;using setf (which understands get as a place description)
;to create indicator fav-book with value harrypotter of symbol aastha.
  
(write (symbol-plist 'aastha))
;using symbol-plist to return aastha(symbol's) plist .
  
(terpri)
(remprop 'aastha 'fav-book)
;using remprop to remove property of symbol aastha
;which has indicator fav-book
  
(write (symbol-plist 'aastha))
(terpri)
(setq x '())
(setf (getf x 'height ) 20)
  
;using setf along with getf to set property of
;indicator height as 20 at place x
(write(eq(getf x 'height) 20))
  
;using eq to check if property of
;indicator height at place x is 20
(terpri)
(remf x 'height)
  
;using remf to remove property 
;of indicator height at place x
(write(eq(getf x 'height) 20))

Output:

(FAV-BOOK HARRYPOTTER OCCUPATION DOCTOR AGE 20)


(OCCUPATION DOCTOR AGE 20)
T
NIL
Arrays in LISP

LISP, is a list processing, is a programming language widely used in working with data
manipulation. LISP allows us to produce single or multiple-dimension arrays using the make-
array function. An array can store any LISP object as its elements.

The index number of the array starts from 0 to the n-th term.

Attributes:

 The setf attribute gives a call to the function.


 The aref attribute allows accessing the name of the array and index value.
 The my-array attribute is used in creating the cells of the array.
 The dotimes attribute allows looping. Looping start from zero to the nth number defined by the
user.
 The tepri attribute is used to produce a new line,
 The initial-content attribute is a sequence of nested structures. 

Example 1:  

// Making a file array

// lisp to print names

(setq myarray (make-array '() 

   :initial-contents 

   '(((Ayush Agarwal) (Piyush Goel)) 

      ((Keshav Kedia) (Gaurav Garg)) 

   ))

(write myarray)

(terpri)

Output:

Example 2:

// Lisp code for array

// Making a file array.lisp

// to print number from 10 to 19 .

(write (setf my-array (make-array '(10))))

(terpri)

(setf (aref my-array 0) 10)

(setf (aref my-array 1) 11)

(setf (aref my-array 2) 12)

(setf (aref my-array 3) 13)

(setf (aref my-array 4) 14)

(setf (aref my-array 5) 15)

(setf (aref my-array 6) 16)

(setf (aref my-array 7) 17)


(setf (aref my-array 8) 18)

(setf (aref my-array 9) 19)

(write my-array)

Output:

Example 3:

//  Printing a table for 0 and 1 

// using LISP array

(setq a (make-array '(2 11)))

(dotimes (i 2)

   (dotimes (j 11)

      (setf (aref a i j) (list i 'x j '= (* i j)))

   )

(dotimes (i 2)

   (dotimes (j 11)

      (print (aref a i j))

   )

Output:
 

Example 4:

// Making a file array.

// lisp to print alphabets from A to Z.

(setq myarray (make-array '() 

   :initial-contents 

   '(((a b c) (d e f)) 

      ((g h i) (j k l)) 

      ((m n o) (p q r) (s t u) (v w x y z)) 

   ))

(write myarray)

(terpri)

Output:
 

You might also like