Artificial Intelligence Notes
Artificial Intelligence Notes
A branch of Computer Science named Artificial Intelligence pursues creating the computers or
machines as intelligent as human beings.
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.
Out of the following areas, one or multiple areas can contribute to build an intelligent system.
What is AI Technique?
In the real world, the knowledge has some unwelcomed properties −
AI Technique is a manner to organize and use the knowledge efficiently in such a way that −
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.
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 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) 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.
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.
Blind search
Uninformed and informed search
Depth first search
Breadth first search
Uniform cost search
Search heuristics
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)
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.
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.
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.
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.
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.
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
Syntax:
(write-line string)
Example:
;this is a comment
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:
A variable can not contain double and single quotes, backslash, comma, colon, semicolon, and
vertical bar.
Example:
A variable can not start with a digit but. it can contain any number of digits
Example:
(write-line "hello")
(terpri)
(write-line "hello99")
(terpri)
(terpri)
(write-line "hello_Geek")
(terpri)
(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.
Functions in LISP are defined using the DEFUN macro. The basic syntax looks like this :
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.
(hello-world)
Output:
Hello, World!
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.
(+ 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"))
(welcome-to-gfg)
(terpri)
(welcome-to-gfg "UserName")
Output:
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.
Attributes Used:
Example 1:
; set value 2 to 78
;addition operation
(princ "addition")
;subtraction operation
(princ "subtraction")
;multiplication operation
(princ "multiplication")
;division operation
(princ "division")
;modulus operation
(princ "modulus")
;increment a by 10
;decrement b by 20
Output:
Example 2:
(terpri)
(terpri)
(terpri)
(terpri)
(terpri)
(terpri)
(princ "mod: ")
(terpri)
(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.
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:
(terpri)
; cons with 1 nil value as argument
(terpri)
(terpri)
Output:
(GEEKSFORGEEKS . IS_BEST)
(999)
(A B)
(A B C)
Lists in LISP:
Syntax:
Example:
(terpri)
(terpri)
(terpri)
(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))
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:
(terpri)
(terpri)
Output:
BEST
GEEKS
(C D)
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 manipulating functions are used to manipulate and return the list of elements
1. car() Function:
Syntax:
Example:
(terpri)
;list of characters
(terpri)
Output:
1
A
2. cdr() Function:
This function is used to display the list of all elements excluding the first element
Syntax:
Example:
;list of characters
(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:
where,
Example:
;insert 100
(terpri)
;list of characters
;insert a
(terpri)
Output:
(100 1 2 3 4 5)
(A B C D E F)
4. list() Function:
Syntax:
Example:
(terpri)
Output:
(100 (1 2 3 4 5) (G E E K S))
5. append() Function:
Syntax:
Example:
(terpri)
(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:
(terpri)
(terpri)
Output:
(5)
((G E E K S))
7. member() Function:
If the value is present in the list, then it will return the list
Syntax:
Example:
(terpri)
(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:
(terpri)
(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:
(terpri)
Output:
2. equal:
This predicate will check the given two arguments are equal or not, if equal it returns T
otherwise nil.
Syntax:
Example:
(terpri)
(terpri)
Output:
NIL
T
3. eq:
This predicate will check will two arguments are identical in the case of sharing the same
memory
Syntax:
Example:
(terpri)
(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:
(terpri)
(terpri)
Output:
NIL
T
5. oddp:
Syntax:
(oddp element)
Example:
(terpri)
(terpri)
Output:
T
NIL
6. zerop:
(zerop element)
Example:
(terpri)
(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:
(terpri)
(terpri)
Output:
NIL
T
8. listp:
Syntax:
(listp element)
Example:
(terpri)
(terpri)
Output:
NIL
T
9. numberp:
This predicate will return if the given argument is number otherwise nil
Syntax:
(numberp element)
Example:
(terpri)
Output:
T
NIL
10. integerp:
Syntax:
(integerp element)
Example:
(terpri)
(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:
(write (rationalp 67 ))
(terpri)
(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:
(terpri)
(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:
(terpri)
(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:
(terpri)
(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:
(terpri)
(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:
(terpri)
(terpri)
Output:
T
NIL
17. arrayp:
Syntax:
(arrayp element)
Example:
;create an array
(terpri)
(terpri)
(terpri)
Output:
#(NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL)
T
NIL
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:
(terpri)
(terpri)
Output:
equal to 100
greater than 50
less than 150
Example 2:
(terpri)
(terpri)
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:
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.
Output:
(terpri)
(terpri)
(terpri)
Output:
when Statement
Syntax:
where,
;set number to 50
;condition check the given number is equal to 50
;statement
)
Output:
Equal to 50
Example 2: LISP Program to check the given number with comparison operators
;set number to 50
;statement
)
(terpri)
;statement
)
(terpri)
;set number to 10
;statement
)
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,
Example: LISP Program to get the particular number when the number is given
;define value to 2
(setq val1 2)
(case val1
Output:
Example: LISP Program to perform an arithmetic operation when a particular key is chosen
;define value1 to 10
;define value2 to 20
;set input to 1
(setq input 1)
(case input
Output:
30
Set input to 3
;define value1 to 10
;define value2 to 20
;set input to 3
(setq input 3)
(case input
Output:
200
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.
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.
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 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.
One character is taken from the input stream and returned as a character object by read-char.
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.
When it is necessary to know precisely which character ended the extended token, the function
read-preserving-whitespace is offered.
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.
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.
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.
It is similar to read-char, but instead of waiting for a character if it doesn’t receive one, it returns
nil right away.
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.
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.
Example :
;LISP- Input
(values)
Output :
read-byte extracts one byte from the binary input stream and returns it as an integer.
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:
This statement will take input from the keyboard and store it in the variable.
Example:
(defun PerimOfCircle()
(terpri)
(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.
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 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.
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.
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.
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 :
(defun DoubledNumber()
(terpri)
(setq n1 (read))
(write n1)
(terpri)
(write double)
(DoubledNumber)
Output :
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:
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
~S followed by S-expressions.
~? Indirection. The next argument must be a string, and the one after it a list.
Example :
(defun PerimOfCircle()
(terpri)
(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:
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,
Example:
(defvar n 3)
(loop
(print n)
(setq n (+ n 1))
(write-line "")
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:
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:
(print x)
(write-line "")
Output:
4. do:
Where,
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:
(write-line "")
Output:
5. dolist:
Syntax:
Where,
listItemVariable => Holds value of each list item during every iteration
list => List to traverse
expressions => Statements to be executed in every iteration
Example:
(print item)
)
(write-line "")
Output:
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.
Output:
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:
Example 1:
:initial-contents
))
)
(write myarray)
(terpri)
Output:
Example 2:
(terpri)
(write my-array)
Output:
Example 3:
(dotimes (i 2)
(dotimes (j 11)
)
(dotimes (i 2)
(dotimes (j 11)
)
Output:
Example 4:
: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: