Ai Lab Manual

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 87

“Artificial Intelligence”

“Artificial Intelligence”
“LAB MANUAL”
LAB #1
Name: Nooria Ijaz
BS-COMPUTERS
8th (F)

Windows User Artificial Intelligence


1. WHAT IS ARTIFICIAL INTELLIGENCE (AI)?
Artificial intelligence (AI) is the simulation of human intelligence processes by
machines, especially computer systems. Specific applications of AI include expert
systems, natural language processing (NLP), speech recognition and machine
vision.

1. Introduction

A machine with the ability to perform cognitive functions such as perceiving,


learning, reasoning and solve problems are deemed to hold an artificial
intelligence. Artificial intelligence exists when a machine has cognitive ability.
The benchmark for AI is the human level concerning reasoning, speech, and
vision.

2. Objective of the Experiment

After completing this lab, the student should be able to:

 Understand the term of Artificial Intelligence.

 Know the history of Artificial Intelligence.

 Know the applications of AI.

3. Concept Map

3.1 Introduction

Artificial Intelligence is composed of two words, Artificial (non-natural) +


Intelligence.

3.1.1 Intelligence

The ability to understand, think & learn.


3.1.1.1 Maze Game Example

The ability to solve a search problem demonstrates intelligence.

3.1.1.2 Time Table Example

The ability to plan and schedule demonstrates intelligence.

3.1.1.3 Height Example

Ability to handle fuzzy questions, different thoughts over same measurements and
same knowledge leads towards

4.1.1.4 Doctor-Patient Example

Ability to use memory efficient and perceive things to react, demonstrates


intelligence.

3.2 Introduction to 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.

As we have seen above intelligence examples, what if a machine perceives?

 A machine searches a maze.

 A machine plans a timetable.


 A machine handles fuzzy questions.

 A machine diagnoses patients.

3.3 History of Artificial Intelligence

3.3.1 Turing Test (1950)

In 1950 Alan Turing performed a Turing test https://www.youtube.com/watch?


v=3wLqsRLvV-c

3.3.2 Chinese Room Experiment

3.3.3 ALVINN (Automatic Land Vehicle in Neural Network)

A self-driving car. 2850 Km driven without driver. Let’s meet ALVINN ->
https://www.youtube.com/watch?v=ilP4aPDTBPE

3.4 Goals of Artificial Intelligence

 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.

3.5 Subsets of Artificial Intelligence

AI programming focuses on three cognitive skills: learning, reasoning and self-


correction.

Learning processes. This aspect of AI programming focuses on acquiring data


and creating rules for how to turn the data into actionable information. The rules,
which are called algorithms, provide computing devices with step-by-step
instructions for how to complete a specific task.
Reasoning processes. This aspect of AI programming focuses on choosing the
right algorithm to reach a desired outcome.

Self-correction processes. This aspect of AI programming is designed to


continually fine-tune algorithms and ensure they provide the most accurate results
possible.
2. WHAT ARE THE USES FOR AI?
AI is ubiquitous today, used to recommend what you should buy next online, to
understand what you say to virtual assistants such as Amazon's Alexa and Apple's
Siri, to recognise who and what is in a photo, to spot spam, or detect credit card
fraud.
3. ARTIFICIAL INTELLIGENCE EXAMPLES

Manufacturing robots
Smart assistants
Proactive healthcare management
Disease mapping
Automated financial investing
Virtual travel booking agent
Social media monitoring
Inter-team chat tool
Conversational marketing bot
Natural Language Processing (NLP) tools

4. WHAT IS Z LANGUAGE?
Z is a model oriented formal specification language based on Zermelo-Fränkel
axiomatic set theory and first order predicate logic. It is a mathematical
specification language, with the help of which natural language requirements
can be converted into mathematical form.
5. WHAT IS PROLOG?
Prolog was one of the first logic programming languages,[7] and remains the
most popular among such languages today, with several free and commercial
implementations available. The language has been used for theorem proving,
[8]
 expert systems,[9] term rewriting,[10] type systems,[11] and automated planning,
[12]
 as well as its original intended field of use, natural language processing.[13]
[14]
 Modern Prolog environments support the creation of graphical user
interfaces, as well as administrative and networked applications.
Prolog is well-suited for specific tasks that benefit from rule-based logical
queries such as searching databases, voice control systems, and filling
templates.
6. WRITE TYPES AND VERSIONS OF PROLOG
SOFTWARE?
GNU-Prolog SWI-Prolog
This document lists the SWI-Prolog data types and relevant information such as
their limits. It is mostly intended for programs that want to examine and/or
exchange arbitrary SWI-Prolog data.
Classical Prolog types

Variable

Integer

Floats

Atoms

Compound terms

SWI-Prolog extensions

Blobs

Strings

Nil ([], empty list)

List cons-cell

Dictionaries
“Artificial Intelligence”
“SWI-PROLOG”
LAB #2
Artificial Intelligence
“SWI- Prolog”

Introduction :
Prolog is a logic programming language. It has important role in
artificial intelligence. Unlike many other programming languages,
Prolog is intended primarily as a declarative programming language.
In prolog, logic is expressed as relations (called as Facts and Rules).
Core heart of prolog lies at the logic being applied. Formulation or
Computation is carried out by running a query over these relations.
Installation in Linux :

1. Using an Internet browser navigate to SWI-Prolog home


page: https://www.swi-prolog.org/ 116
2. Mouse over Download
3. Click SWI-Prolog
This will take you download page: https://www.swi-
prolog.org/Download.html 59
4. Under Available versions click Development release

This will take you to SWI-Prolog development downloads


page: https://www.swi-prolog.org/download/devel 22
5. Under Binaries click on the (64-bit) version. For this example it
currently is SWI-Prolog 8.1.12-1 for Microsoft Windows (64
bit)

a. Select I understand
b. Click Download swipl-8.1.12-1.x64.exe
6. This will open a Save As dialog on Windows. Select a directory
and click Save
In the lower left of the Internet browser screen a dialog will appear
with the name of the file

7. Click on the   and select Open


A Windows security dialog should appear

Windows Defender SmartScreen prevented an unrecognized app from


starting. Running this app might put your PC at risk.
9. Click More info to reveal the option to run the executable to
install SWI-Prolog
10. Click Run anyway
This will open a User Account Control dialog (Sorry for not
getting an image, would have to disable some security features
to get it).
11. Click Yes
This will start the install wizard 1
12. .
Note: If there was a previous version of SWI-Prolog installed a
dialog will ask
Do you want to uninstall the old version before installing the
new one?
Any option is valid.
12. Click Next
13. Click I Agree

14. Click Next
15. Click Next

16. Click Next
17. Click Install

17 a. If during the install you get a dialog noting Error opening file for
writing: ...

Check to make sure you do not have an application with a lock on a


file in the directory, e.g. File Explorer is open to the
directory C:\Program Files\swipl and clear the lock. If you cannot find
the lock then a reboot is necessary.
18. Click Finish

To start SWI-Prolog

In lower left click on start button  

Then at top of dialog

click SWI-Prolog
This will start SWI-Prolog console
How to uninstall SWI-Prolog.
Note: SWI-Prolog does not require the previous version be
uninstalled. If a previous version is installed then during the install an
additional dialog will appear asking if you want to uninstall the
previous version. You can answer either Yes or No depending upon
your preference; the install should complete successfully either way.
1. Using Windows File Explorer navigate to C:\Program
Files\swipl
2. Click on Uninstall.exe
3. For User Account Control dialog click Yes.
4. Click Uninstall

5. Click Close
NB The directory should be either empty or have only a few
files left in it. During this example the only file left
was C:\Program Files\swipl\boot64.prc

Syntax and Basic Fields :


In prolog, We declare some facts. These facts constitute the
Knowledge Base of the system. We can query against the Knowledge
Base. We get output as affirmative if our query is already in the
knowledge Base or it is implied by Knowledge Base, otherwise we
get output as negative. So, Knowledge Base can be considered similar
to database, against which we can query. Prolog facts are expressed in
definite pattern. Facts contain entities and their relation. Entities are
written within the parenthesis separated by comma (, ). Their relation
is expressed at the start and outside the parenthesis. Every fact/rule
ends with a dot (.). So, a typical prolog fact goes as follows :
Format : relation(entity1, entity2, ....k'th entity).

Example :
friends(raju, mahesh).
singer(sonu).
odd_number(5).

Explanation :
These facts can be interpreted as :
raju and mahesh are friends.
sonu is a singer.
5 is an odd number.

Key Features :
1. Unification : The basic idea is, can the given terms be made to
represent the same structure.
2. Backtracking : When a task fails, prolog traces backwards and
tries to satisfy previous task.
3. Recursion : Recursion is the basis for any search in program.
Running queries :
A typical prolog query can be asked as :
Query 1 : ?- singer(sonu).
Output : Yes.

Explanation : As our knowledge base contains


the above fact, so output was 'Yes', otherwise
it would have been 'No'.

Query 2 : ?- odd_number(7).
Output : No.

Explanation : As our knowledge base does not


contain the above fact, so output was 'No'.

Advantages :
1. Easy to build database. Doesn’t need a lot of programming effort.
2. Pattern matching is easy. Search is recursion based.
3. It has built in list handling. Makes it easier to play with any
algorithm involving lists.
Disadvantages :
1. LISP (another logic programming language) dominates over prolog
with respect to I/O features.
2. Sometimes input and output is not easy.
Applications :
Prolog is highly used in artificial intelligence(AI). Prolog is also used
for pattern matching over natural language parse trees.
“Artificial Intelligence”
“SWI-PROLOG”
LAB #3
Windows User Artificial Intelligence
QUESTION:
W3HOW TO WRITE MULTIPLE RULES IN PROLOG?
Week2 and week3
Example 1 : Below food table shows the facts, rules, goals and their
english meanings.
English
Facts
meanings   
// burger is
food(burger).
a food
// sandwich
food(sandwich).
is a food
// pizza is a
food(pizza).
food
// sandwich
lunch(sandwich).
is a lunch
// pizza is a
dinner(pizza).
dinner
Rules
// Every
food is a
meal(X) :- food(X). meal OR
Anything is
a meal if it
is a food
Queries / Goals
// Is pizza a
?- food(pizza).
food?
// Which
?- meal(X), lunch(X). food is meal
and lunch? 
// Is
sandwich a
dinner?
?- dinner(sandwich).
Example 2 : Below student-professor relation table shows the facts,
rules, goals and their english meanings.
Facts English meanings 
studies(charlie, csc135). // charlie studies csc135
studies(olivia, csc135). // olivia studies csc135
studies(jack, csc131).   // jack studies csc131
studies(arthur, csc134). // arthur studies csc134
teaches(kirke, csc135).   // kirke teaches csc135
teaches(collins, csc131).  // collins teaches csc131
teaches(collins, csc171).  // collins teaches csc171
teaches(juniper, csc134). // juniper teaches csc134
 
Rules
professor(X, Y) :- // X is a professor of Y if
teaches(X, C), studies(Y, X teaches C and Y studies
C). C.

Queries / Goals 
// charlie studies what?
?- studies(charlie, What). OR
What does charlie study?
?- professor(kirke, // Who are the students of
Students). professor kirke.

From Example 1 :
(1)   ?- meal(X), dinner(X).
(2)   ?- meal(What).
(3)   ?- meal(X), dinner(Y).
From Example 2 :
(1)   ?- studies(Who, csc135).    ( hint : after getting first
solution type ' ; ' to find all the possible solutions) 
Fun Bonus : Using Example-2 just copy paste below
query and see the result -
?- studies(charlie, Which), teaches(Who,Which),
write('charlie studies '), write(Which), write(' and
professor '), write(Who), write(' teaches '),
write(Which). 
“Artificial Intelligence”
“SWI-PROLOG”
LAB #4
Week04 16-3-2021

Windows User Artificial Intelligence


“APRORI ALGORITHM”
Practical #1
Write at least 05 facts related to medicine .
for example i. medicine(pandol,disprin).
ii.
iii.
iv.
v.
steps:
o open prolog
o write facts to make pl file “named medicine”
o pass two arguments
o consult pl file (from knowledge base)
o query all facts (query window)
o take screen shot
o make your word file

Practical #2
A fact is a predicate expression that makes a
declarative statement about the problem
domain. Whenever a variable occurs in a
Prolog expression, it is assumed to
be universally quantified. Note that all Prolog
sentences must end with a period.
steps:
o open prolog
o write facts to make pl file “named medicine”
o pass two arguments
o consult pl file (from knowledge base)
o query all facts (query window)
o take screen shot
o make your word file
practical statement
create following facts in prolog file.
Facts English meaning
1. likes(ALI, bilal). /* ali likes bilal*/

2. likes(X, bilal). /* Everyone likes bilal */

3. likes(ali, Y). /* ali likes everybody */

4. likes(ali, Y) , likes(Y, ali). /* ali likes everybody and everybody


likes ali */

http://www.cs.trincoll.edu/~ram/cpsc352/notes/prolog/factsrules.html

not(likes(john,pizza)). /* John does not like pizza */


likes(john,susie) :- likes(john,mary)./* John likes Susie if John likes
Mary.

Rules
(A-STAR ALGO. )
CODE:
OUTPUT:
“Artificial Intelligence”
“SWI-PROLOG”
LAB #5
Windows User Artificial Intelligence
“Variables and Unification”
1. Introduction

One of Prolog's most powerful features is its built-in pattern-matching


algorithm, unification. For all of the examples we have seen so far,
unification has been relatively simple. The way in which Prolog
matches two terms is called unification. The idea is similar to that of
unification in logic: we have two terms and we want to see if they can
be made to represent the same structure.

The purpose of lab is to be used to help learn the essential, basic


concepts of unification and backtracking. The sample programs have
been especially chosen to help promote the use of Prolog
programming in an artificial intelligence course.
Relevant Lecture Readings:
a) Revise Lecture No. 5 and 6
2. Activity Time boxing
Table 1: Activity Time Boxing Task No. Activity Name Activity time
Total Time 5.1 Evaluation of Design 15 mins 15 mins 6.2 Setting-up
Prolog 5 mins 5 mins 6.3 Walkthrough Task 25 mins 25 mins 7
Practice tasks 25 + 15 + 20 (mins) 60 mins 8 Evaluation Task 65 min
65 mins Total Time 170 Minutes

3. Objective of the Experiment After completing this lab, the student


should be able to:  Clearly understand the use of Unification. 
Understand the concept Backtracking.  Use unification in swi-
prolog.
4. Concept Map
Unification is the process of matching two terms and backtracking is
when it doesn't match the query, as a result, Prolog goes back to its
last choice point and sees if there is an alternative solution.
4.1 Unification The way in which Prolog matches two terms is called
unification. The idea is similar to that of unification in logic: we have
two terms and we want to see if they can be made to represent the
same structure. Suppose we have a fact in our database:

eats(fred,mangoes). How do we ask what fred eats. We could type in


something like

? - eats(fred,what).
Lab 3: Unification and Backtracking

However, Prolog will say no. The reason for this is that what does not
match with mangoes. In order to match arguments in this way we
must use a Variable. The process of matching items with variables is
known as unification.

Variables are distinguished by starting with a capital letter. Here are


some examples:

X /* a capital letter */ VaRiAbLe /* a word - it be made up or


either case of letters */ My_name /* we can link words together via
'_' (underscore) */

Thus returning to our first question we can find out what fred eats by
typing

? - eats(fred,What).
What=mangoes
yes
4.2 Unification Examples

Let's consider some examples using facts. First consider the following
database.

loves(john,mary). loves(fred,hobbies).

Question Response loves(john,Who). Who=mary /* yes , Who


gets bound to mary */ yes loves(arnold,Who). no /* no,
arnold doesn't match john or fred */ loves(fred,Who). Who = hobbies
/* Note the to Prolog Who is just the name of a variable, it */ yes

How do we say something like "What does Fred eat"? Suppose we


had the following fact in our database:

eats(fred,mangoes).
How do we ask what fred eats. We could type in something like

?- eats(fred,what).

However Prolog will say no. The reason for this is that what does not
match with mangoes. In order to match arguments in this way we
must use a Variable. The process of matching items with variables is
known as unification. Variables are distinguished by starting with a
capital letter. Here are some examples:

X /* a capital letter */

VaRiAbLe /* a word - it be made up or either case of letters */

My_name /* we can link words together via '_' (underscore) */


Thus returning to our first question we can find out what fred eats by
typing

?- eats(fred,What).

What=mangoes

yes

As a result of this query, the variable What has matched (or unified)
with mangoes. We say that the variable What now has the binding
mangoes. When we pose a query, if the query is successful, Prolog
prints both the variable and the variable name, as we see above.
Variable Examples 1
Let's consider some examples using facts. First consider the following
database.

loves(john,mary).

loves(fred,hobbies).

Now let's look at some simple queries using variables

?- loves(john,Who). /* Who does john love? */

Who=mary /* yes , Who gets bound to mary */

yes /* and the query succeeds*/

?- loves(arnold,Who) /* does arnold love anybody */

no /* no, arnold doesn't match john or fred */

?- loves(fred,Who). /* Who does fred love */

Who = hobbies /* Note the to Prolog Who is just the name of a variable,
it */
“Artificial Intelligence”
“SWI-PROLOG”
“Clusteringwith
LAB #6WEKA
Explorer”
Windows User Artificial Intelligence
1. Open a terminal window from the left bar. Go to
directory /opt/weka-3-6-13, then type command : java
–jar weka.jar.

2. Fire up WEKA to get the GUI Chooser panel. Select


Explorer from the four choices on the right side.
3. We are on Preprocess now. Click the Open file button to
bring up a standard dialog through which you can select a file.
Choose the telco_labFour.csv file.
4. You could ignore irrelevant attributes during the clustering
process, like custIds. To identify redundant attributes, we
could check the correlation from Visualization of the data set
under Visualize Tab. age and agecat are correlated. One of
them should be ignored. We keep age for clustering purpose;
also ed (removing edcat), then we have 8 attributes left for
clustering (we will ignore custIds, agecat and edcat when we
perform clustering.
5. Before we do clustering with Weka, we need to normalize
your numeric data values (use Normalize filter). Since we
have the class label, we would like to set it to nominal before
normalization. This information will be used to evaluate the
clustering performance.
6. To perform clustering on the data set, click Cluster tab and
choose SimpleKMeans algorithm. We set k = 2 for this data
set. Choose Classes to clusters evaluation and select the last
attribute as class label. Check Store clusters for visualization.
Click Ignore attributes and select custIds, agecat, edcat, and
the last attribute churn. Then click Start.
1839+623 = 2462
7. You could visualize the clustering results by right-clicking
the result list and choose visualize clusters assignments. You
could select different combination of two attributes as X and
Y.
8. You could save the clustering results by clicking Save
button on the Visualization panel. The results are saved
in a .arff file. You could use Weka to open it and view
the results.
9. If the data set has no class labels, then when you perform
clustering on the data set, choose Use Training Dataset as
Cluster mode.
10. HierarchicalClusterer implements agglomerative (bottom-
up) generation of hierarchical clusters. Several different link
types, which are ways of measuring the distance between
clusters, are available as options.
11. Since the Hierarchical Clustering algorithm builds a tree
for the whole dataset, let’s practice this algorithm on a smaller
dataset due to the memory space
limitation. Open glass.arff dataset used in the previous lab,
first normalize all the numeric values in the dataset into [0,1].
Then chose HierarchicalCluster cluster. Since this datset has 6
classes, we set numClusters as 6. To save time, we set
printNewick as False.
12. After you run the clustering algorithm, you could right
click the clustering result and check its hierarchical tree by
clicking Visualize Tree.
13. Since the performance of HierarchicalClustering is not
good, we could run Kmeans algorithm on the same dataset
and compare their performance. Do not forget to set the
number of clusters to 6.
14. Save the clustering results as glass_kmeans_result.arff file
and reopen it with
“Artificial Intelligence”
“SWI-PROLOG”
LAB #8
Windows User Artificial Intelligence
“CONJUNCTION”
For conjunction, comma ',' is used and it is read as 'and'. In prolog, goals can
be written like this as conjunction?- likes(john, mary), likes(mary,
john). Here we have given two subgoals in one query using conjunction. For
answering the query as success Prolog has to match and satisfy each sub goals
with the knowledge base (i.e. Facts and Rules).
Prolog repeatedly tries to find match and satisfy the goals by looking to the
knowledge base in top-down manner i.e. backtracking. When goals are given
as conjunction, Prolog finds the match and satisfy goals in conjunction, in left-
to-right manner.
That means, for this query ?- likes(john, mary), likes(mary, john). prolog will
first match and satisfy the left most goal i.e. likes(john, mary) and then the
second goal. If any of the subgoals does not satisfy, then query will be answered
as failure. 

Examples Of Conjunction :
Conjunction in Rule :
    likes(mary, day) :- sunny, warm.
         // Read as : mary likes a day, if it is sunny and warm.
Conjunction in Goal :
    ?- place(sunny), place(windy).
        // Is place sunny and windy? OR Is place sunny? and Is
place windy? 
“Artificial Intelligence”
“SWI-PROLOG”
LAB #9
Windows User Artificial Intelligence
SWI- PROLOG PERFORM
ARITHEMATIC OPERATIONS:
Don’t perform
“Artificial Intelligence”
“SWI-PROLOG”
LAB #10
Windows User Artificial Intelligence
“ LISTS and use of LIST”
“head & tail in LIST” .

Introduction
In Prolog list is an ordered sequence of components, where components can be
variables, constants, compound terms, numbers or another list.
Syntax : [components] - write your components within square brackets.
Examples : different ways to write list
[1,2,3,4].
[nova, james, 2].
[X, Y, james].
[A, [p, n, c], 4].
[likes(X,Y), cat(fur)].
[] - an empty list

How list works ? use of head & tail in prolog.


Learning question
 What is LIST used in PROLOG?
 How LIST helps in developing sequence or order of element?
 What are components used in LIST?
 What are different ways to write list prolog software?

Lab objective
 This lab will give overview of list used in prolog to make data order or
sequence.
 The student should be able to: Understand the term LIST,
COMPONENETS, ORDER, ELEMENTS
 Students also be able to create order element LIST.

Activity Time: 120 min


Example:

Head and Tail of the lists :


head : the 1st element of the list.
tail : all elements of the list except the 1st one
Syntax : [H | T]
For example:
(1) In list [1,2,3,4] head is 1 and tail is [2,3,4]
(2) In list [a] head is a and tail is [].
(3) In list [likes(john, mary), X , 1, 2] head is likes(john, mary) and tail is
[X, 1, 2].
(4) In list [A, [p, n, c], 4] head is A and tail is [[p, n, c],4]
(5) In list [[1, 2], a, b ] head is [1, 2] and tail is [a, b]
Note : In above examples tails are always a list. [H | T] = [1, 2, 3, 4], H is 1 and
T is [2, 3, 4] = [1 | [2, 3, 4]]
Valid: [1 | [2, 3]] [[1,2] | [3, 4]] Invalid: [1, 2 | 3]
Examples –
How do these terms unify ? - Read Unification Instantiation
(1) [A | [b, c]] = [X | Y]
Prolog Responses : ?- [X|Y] = [A | [b, c]] . X = A, Y = [b, c].
?- [A | [b, c]] = [X|Y]. A = X, Y = [b, c].
(2) [B, [p, n, c], 4] = [X | Y]. 
Prolog Response : ?- [B, [p, n, c], 4] = [X | Y]. B = X, Y = [[p, n, c], 4].
(3) [likes(john, mary), X , 1, 2] = [Head | Tail].

Prolog Respsonse : ?- [likes(john, mary), X , 1, 2] = [Head | Tail].


Head = likes(john, mary),
Tail = [X, 1, 2].
(4) Try it yourself. [[1, 2], a, b ] = [Head | Tail].
(5) Try it yourself. [john] = [Head | Tail].
Sample Prolog Program using List :
Program : /* Facts */ list([p, q, r]).
/* Rules */ what_is([Head | Tail]):- list([Head|Tail]).
Query Prompt : ?- what_is([Head|Tail]). Head = p, Tail = [q, r].
“Artificial Intelligence”
“SWI-PROLOG”
LAB #11
Windows User Artificial Intelligence
LISP LAB TASK:
1.PREFIX NOTATION
2. RUN IT WITH VARIABLES:
3.RUN CODE INSTEAD OF defvar rathen than
setq:
4.Run all codes of lisp :
“Functions”
Calling Functions
Defining functions is only half the battle. Functions don't do anything until
you call them, i.e., tell them to run. Calling a function is also known as invocation.

The most common way of invoking a function is by evaluating a list. For example,
evaluating the list (concat "a" "b") calls the function concat with arguments "a" and "b".
See Evaluation, for a description of evaluation.
When you write a list as an expression in your program, you specify which function to
call, and how many arguments to give it, in the text of the program. Usually that's just
what you want. Occasionally you need to compute at run time which function to call. To
do that, use the function funcall. When you also need to determine at run time how many
arguments to pass, use apply.
— Function: funcall function &rest arguments
funcall calls function with arguments, and returns whatever function returns.
Since funcall is a function, all of its arguments, including function, are evaluated
before funcall is called. This means that you can use any expression to obtain the
function to be called. It also means that funcall does not see the expressions you write for
the arguments, only their values. These values are not evaluated a second time in the act
of calling function; the operation of funcall is like the normal procedure for calling a
function, once its arguments have already been evaluated.
The argument function must be either a Lisp function or a primitive function. Special
forms and macros are not allowed, because they make sense only when given the
unevaluated argument expressions. funcall cannot provide these because, as we saw
above, it never knows them in the first place.
If you need to use funcall to call a command and make it behave as if invoked
interactively, use funcall-interactively (see Interactive Call).

(setq f 'list)

⇒ list

(funcall f 'x 'y 'z)

⇒ (x y z)

(funcall f 'x 'y '(z))

⇒ (x y (z))

(funcall 'and t nil)

error--> Invalid function: #<subr and>

Compare these examples with the examples of apply.


— Function: apply function &rest arguments
apply calls function with arguments, just like funcall but with one difference: the last
of arguments is a list of objects, which are passed to function as separate arguments,
rather than a single list. We say that apply spreads this list so that each individual
element becomes an argument.
apply returns the result of calling function. As with funcall, function must either be a Lisp
function or a primitive function; special forms and macros do not make sense in apply.
(setq f 'list)

⇒ list

(apply f 'x 'y 'z)

error--> Wrong type argument: listp, z

(apply '+ 1 2 '(3 4))

⇒ 10

(apply '+ '(1 2 3 4))

⇒ 10

(apply 'append '((a b c) nil (x y z) nil))

⇒ (a b c x y z)

For an interesting example of using apply, see Definition of mapcar.

Sometimes it is useful to fix some of the function's arguments at certain values, and
leave the rest of arguments for when the function is actually called. The act of fixing
some of the function's arguments is called partial application of the function1. The result
is a new function that accepts the rest of arguments and calls the original function with
all the arguments combined.

Here's how to do partial application in Emacs Lisp:

— Function: apply-partially func &rest args


This function returns a new function which, when called, will call func with the list of
arguments composed from args and additional arguments specified at the time of the
call. If func accepts n arguments, then a call to apply-partially with m < n arguments will
produce a new function of n - m arguments.
Here's how we could define the built-in function 1+, if it didn't exist, using apply-
partially and +, another built-in function:

(defalias '1+ (apply-partially '+ 1)

"Increment argument by one.")

(1+ 10)
⇒ 11

It is common for Lisp functions to accept functions as arguments or find them in data
structures (especially in hook variables and property lists) and call them
using funcall or apply. Functions that accept function arguments are often
called functionals.

Sometimes, when you call a functional, it is useful to supply a no-op function as the
argument. Here are two different kinds of no-op function:

— Function: identity arg

This function returns arg and has no side effects.

— Function: ignore &rest args
This function ignores any arguments and returns nil.
Lisp Defining Function:
Program #1
Program #2
Lisp Rest Parameters:
Program #1
Lisp Keyword Parameters:
Program #1

Lisp Returning Values Function:


Program #1
Program #2
Lisp Lambda Functions:
Program #1

Lisp Mapping Functions


Program #1

Program #2
Program # 3
• The do construct is also used for performing iteration
using LISP. It provides a structured form of iteration.
• The syntax for do statement −
• The dotimes construct allows looping for
some fixed nuber of iterations.
• For example, Create a new source code file named main.lisp and
type the following code in it:

You might also like