SlideShare a Scribd company logo
1
CS 2740 Knowledge Representation M. Hauskrecht
CS 2740 Knowledge Representation
Lecture 2
Milos Hauskrecht
milos@cs.pitt.edu
5329 Sennott Square
Introduction to LISP
CS 2740 Knowledge Representation M. Hauskrecht
LISP language
LISP: LISt Processing language
• An AI language developed in 1958 (J. McCarthy at MIT)
• Special focus on symbolic processing and symbol
manipulation
– Linked list structures
– Also programs, functions are represented as lists
• At one point special LISP computers with basic LISP
functions implemented directly on hardware were
available (Symbolics Inc., 80s)
LISP today:
• Many AI programs now are written in C,C++, Java
– List manipulation libraries are available
2
CS 2740 Knowledge Representation M. Hauskrecht
LISP language
LISP Competitors:
• Prolog, Python
• but LISP keeps its dominance among high level (AI)
programming languages
Current LISP:
• Common Lisp
• Scheme
are the most widely-known general-purpose Lisp dialects
Common LISP:
• Interpreter and compiler
• CLOS: object oriented programming
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial
Syntax:
• Prefix notation
– Operator first, arguments follow
– E.g. (+ 3 2) adds 3 and 2
A lot of parentheses
• These define lists and also programs
• Examples:
– (a b c d) is a list of 4 elements (atoms) a,b,c,d
– (defun factorial (num)
(cond ((<= num 0) 1)
(t (* (factorial (- num 1)) num))
))
3
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: data types
Basic data types:
• Symbols
– a
– john
– 34
• Lists
– ( )
– (a)
– (a john 34)
– (lambda (arg) (* arg arg))
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial
For each symbol lisp attempts to find its value
> (setq a 10) ;; sets a value of symbol a to 10
10
> a ;; returns the value of a
10
Special symbols:
> t ;; true
T
> nil ;; nil stands for false or
NIL
> ( ) ;; an empty list
NIL
4
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial
Lists represent function calls as well as basic data structures
> (factorial 3)
6
> (+ 2 4)
6
> (setq a ‘(john peter 34)) ;; quote means: do not eval the argument
(john peter 34)
> (setq a ‘((john 1) (peter 2)))
((john 1) (peter 2))
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: lists
List representation:
• A singly linked list
> (setq a ‘(john peter))
(john peter)
> (car a)
john
> (cdr a)
(peter)
car
cdr
5
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: list
List building functions
> (cons ‘b nil) ;; quote means: do not eval the argument
(b)
> (setq a (cons ‘b (cons ‘c nil)) ;; setq a is a shorthand for set ‘a
(b c)
> (setq v (list ‘john 34 25))
(john 34 25)
> (setq v (list a 34 25))
((b c) 34 25)
> (append ‘(1 2) ‘(2 3))
(1 2 2 3)
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial
List copying
> (setq foo (list 'a 'b 'c))
(a b c)
> (setq bar (cons 'x (cdr foo)))
(x b c)
> foo
(a b c) ;; (cdr foo) makes a copy of the remaining list before
cons
> bar
(x b c)
• Car and cdr operations are nondestructive.
6
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: lists
> (setq bar ‘(a b c))
(a b c)
> (setq foo (cdr bar))
(b c)
> (rplaca foo ‘u) ;; replaces car component of foo (destructive op)
(u c)
> foo
(u c)
> bar
(a u c)
> (rplacd foo ‘(v)) ;; replaces cdr component of foo (destructive)
(u v)
> bar
(a u v)
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial
The same effect as with rplaca and rplacd can be achieved
with setf
> (setq bar ‘(a b c))
(a b c)
> (setq foo (cdr bar))
(b c)
> (setf (cadr bar) ‘u)
u
> bar
(a u c)
> foo
(u c)
7
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial
Evaluation rules:
• A symbol value is sought and substituted
• A quoted value is kept untouched
> (setq a 12)
12
> (setq b (+ a 4))
16
> (setq b ‘(+ a 4))
(+ a 4)
> (eval b) ;; explicit evaluation call
16
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: functions and predicates
Some useful functions and predicates:
> (setq a ‘(1 2 3 4 5))
(1 2 3 4 5)
> (length a) ;; gives the list length of the argument
5
> (atom ‘a) ;; checks if the argument is an atom
T
> (atom a)
NIL
> (listp ‘a) ;; checks if the argument is a list
NIL
> (listp a)
T
8
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: function definition
Definition of a function
(defun <f-name> <parameter-list> <body>)
>(defun square (x)
(* x x))
SQUARE
>(square 2)
4
>(square (square 2))
16
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial
Definition of a function
(defun <f-name> <parameter-list> <body>)
<body> can be a sequence of function calls, the function returns
the value of the last call in the sequence
> (defun foo (a)
(setq b (+ a 1))
(setq c (+ a 2))
c)
FOO
> (foo 2)
4
9
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: conditionals
Cond statement: sequentially tests conditions, the call
associated with the first true condition is executed
> (defun abs (a)
(cond ((> a 0) a)
(t (- a))))
ABS
> (abs 2)
2
> (abs -3)
3
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial
if statement:
(if <test> <then> <else>)
> (defun abs (a)
(if (> a 0) a (- a)))
ABS
> (abs 2)
2
> (abs -3)
3
10
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: equality
4 equality predicates: =, equal, eq, eql
> (= 2 4/2) ;; used for numerical values only
T
> (setf a '(1 2 3 4))
(1 2 3 4)
>(setf b '(1 2 3 4))
(1 2 3 4)
>(setf c b)
(1 2 3 4)
> (equal a b) ;; equal is true if the two objects are isomorphic
T
> (equal c b)
T
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: equalities
>(eq a b) ;; eq is true if the two arguments point to the
same object
NIL
>(eq b c)
T
11
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: nil
Nil represents False and an empty list
> (null nil) ;; tests if the argument is NIL
T
> (null ( ))
T
> (null ‘(a b))
NIL
> (not ‘(a b))
NIL
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: functions
Logical operators: and, or
> (and NIL T)
NIL
> (and T 2 3)
3
> (or nil (= 5 4))
NIL
> (or nil 5)
5
12
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: recursion
Recursive function definitions are very common in LISP
> (defun factorial (num)
(cond ((<= num 0) 1)
(t (* (factorial (- num 1)) num))
))
FACTORIAL
> (factorial 4)
24
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: recursion
Recursive function definitions are very common in LISP
> (defun check_lists (lis)
(cond ((null lis) nil)
(t (cons (listp (car lis)) (check_lists (cdr lis))))))
CHECK_LISTS
> (check_lists (list ‘a ‘(1 2) 3 ‘(a b c) ‘(a)))
(NIL T NIL T T)
13
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: local and global variables
> (setq a 12)
12
> (defun foo (n)
(setq a 14)
(+ n 2))
FOO
> a
12
> (foo 3)
5
> a
14
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: local variables
Defining local variables with let
> (setq a 7) ;store a number as the value of a symbol
7
> a ;take the value of a symbol
7
> (let ((a 1)) a) ;binds the value of a symbol temporarily to 6
1
> a ;the value is 7 again once the let is finished
7
> b ;try to take the value of a symbol which has no value
Error: Attempt to take the value of the unbound symbol B
14
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: local variables
Defining local variables with let and let*
> (let ((a 5) ;; binds vars to values locally
(b 4))
(+ a b))
9
> (let* ((a 5) ;; binds vars sequentially
(b (+ a 2))
(+ a b))
12
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: functions revisited
Standard function – all parameters defined
(defun fact (x)
(if (> x 0)
(* x (fact (- x 1)))
1))
But it is possible to define functions:
• with variable number of parameters,
• optional parameters and
• keyword-based parameters
15
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: functions revisited
Functions with optional parameters
> (defun bar (x &optional y) (if y x 0))
BAR
> (defun baaz (&optional (x 3) (z 10)) (+ x z))
BAAZ
> (bar 5)
0
> (bar 5 t)
5
> (baaz)
13
> (baaz 5 6)
11
> (baaz 5)
15
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: functions revisited
Functions with variable number of parameters
> (defun foo (x &rest y) y) ;; all but the first parameters are put
;; into a list
FOO
> (foo 3)
NIL
> (foo 1 2 3)
(2 3)
> (foo 1 2 3 4 5)
(2 3 4 5)
16
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: functions revisited
Functions with ‘keyword’ parameters
> (defun foo (&key x y) (cons x y))
FOO
> (foo :x 5 :y ‘(3))
(5 3)
> (foo :y ‘(3) :x 5)
(5 3)
> (foo :y 3)
(NIL 3)
> (foo)
(NIL)
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: arrays
List is a basic structure; but arrays and structures are
supported
> (setf a (make-array ‘(3 2)) ;; make a 3 by 2 array
#2a((NIL NIL) (NIL NIL) (NIL NIL))
> (aref a 1 1)
NIL
> (setf (aref a 1 1) 2)
2
> (aref a 1 1)
2
17
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: structures
>(defstruct weather
temperature
rain
pressure)
WEATHER
> (setf a (make-weather)) ;; make a structure
#s(WEATHER :TEMPERATURE NIL :RAIN NIL :PRESSURE NIL)
> (setf a (make-weather :temperature 35))
#s(WEATHER :TEMPERATURE 35 :RAIN NIL :PRESSURE NIL)
> (weather-temperature a) ;; access a field
35
> (weather-rain a)
NIL
> (setf (weather-rain a) T) ;; set the value of a field
T
> (weather-rain a)
T
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: iterations
Many ways to define iterations
Commands:
• loop
• dolist
• dotimes
• do, do*
Also we can write compactly the code for repeated
application of function to elements of the list:
• mapc, mapcar
18
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: iterations
Iterations: loop
> (setq a 4)
4
> (loop (setq a (+ a 1))
(when (> a 7) (return a))) ;; return exists the loop
8
> (loop (setq a (- a 1))
(when (< a 3) (return)))
NIL
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: iterations
Iterations: dolist
> (dolist (x '(1 2 3 4)) (print x))
1
2
3
4
NIL ;; NIL is returned by dolist
>
19
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: iterations
Iterations: dotimes
> (dotimes (i 4) (print i)) ;; starts from 0 and continues till
limit 4
0
1
2
3
4
NIL ;; returns NIL
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: iterations
Iterations: do
> (do ((x 1 (+ x 1)) ;; variable, initial value, next cycle update
(y 1 (* y 2))) ;; the same
((> x 5) y) ;; end condition, value do returns
(print (list x y)) ;; body of do – a sequence of operations
(print ‘next))
(1 1)
NEXT
(2 2)
NEXT
(3 4)
NEXT
(4 8)
NEXT
(5 16)
NEXT
32
20
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: iterations
Iterations: do *
> (do* ((x 1 (+ x 1)) ;; variable, initial value, next cycle update
(y 1 (* x 2))) ;; <<< --- update based on x
((> x 5) y) ;; end condition, value do returns
(print (list x y)) ;; body of do – a sequence of operations
(print ‘next))
(1 1)
NEXT
(2 4)
NEXT
(3 6)
NEXT
(4 8)
NEXT
(5 10)
NEXT
12
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: mapcar
Repeated application of a function to elements of the list
> (mapcar #’oddp ‘(1 2 3 4 5)) ;; named function
(T NIL T NIL T)
> (mapcar #’(lambda(x) (* x x)) ‘(1 2 3 4 5)) ;;temp function
(1 4 9 16 25)
21
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial
Evals and function calls
• A piece of code can be built, manipulated as data
• What if we want to execute it?
> (setq b ‘(+ a 4))
(+ a 4)
> (eval b) ;; explicit evaluation call
16
> (funcall #’+ 2 4) ;; calls a function with args
6
> (apply #’+ 2 ‘(5 6)) ;; calls a function with args
(last args as a list)
13
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: input/output
You can input/output data to:
• standard input/output,
• string or
• file
A number of functions supported by the Lisp:
• (read) ;; reads the input from the standard input
• (print ‘a) ;; prints to the standard output
• (scanf …) (printf …) (format …) for formatted input and output
• (open ..) (close ..) for opening and closing the files
• (load ..) reads and executes the file
22
CS 2740 Knowledge Representation M. Hauskrecht
LISP tutorial: program calls
Assume you have your lisp code ready in the .lisp file
This is how you load it
(load "~/private/lsp/file-to-load.lisp")
… and you can call another load from it as well
CS 2740 Knowledge Representation M. Hauskrecht
Running LISP for CS Students
• Remotely login via ssh to elements.cs.pitt.edu
• LISP is installed in the following directory:
/usr/local/contrib/cmucl-19d/
• You can run lisp from linux by typing /usr/local/contrib/cmucl-
19d/bin/lisp
– You may want to provide a path to the lisp directory so that the
executable is seen from anywhere
– To do this, edit your .cshrc.custom file under your home
directory and add the following line:
set path = ($path /usr/local/contrib/cmucl-19d/bin)
• Use the command (quit) to quit LISP
23
CS 2740 Knowledge Representation M. Hauskrecht
Running LISP for Non-CS Students
• Remotely login via ssh to unixs.cis.pitt.edu
• LISP is installed in the following directory: /usr/pitt/franz-lisp/
• You can run lisp from unix by typing: /usr/pitt/franz-lisp/mlisp
– You may want to provide a path to the lisp directory so that the
executable is seen from anywhere
– To do this, edit your .cshrc file under your home directory and add the
following line:
set path = ($path /usr/pitt/franz-lisp)
• If .cshrc is read-only, then add write permission with the
command: chmod u+w .cshrc
• Use the command (exit) to quit LISP
Ad

More Related Content

What's hot (19)

Stack and queue
Stack and queueStack and queue
Stack and queue
Katang Isip
 
LR Parsing
LR ParsingLR Parsing
LR Parsing
Eelco Visser
 
Presentation1
Presentation1Presentation1
Presentation1
Saurabh Mishra
 
Lab lect03 arith_control
Lab lect03 arith_controlLab lect03 arith_control
Lab lect03 arith_control
MPDS
 
Bottomupparser
BottomupparserBottomupparser
Bottomupparser
Royalzig Luxury Furniture
 
LR parsing
LR parsingLR parsing
LR parsing
ichikaz3
 
Lec06
Lec06Lec06
Lec06
siddu kadiwal
 
Single linked list
Single linked listSingle linked list
Single linked list
jasbirsingh chauhan
 
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative Programmers
Chris
 
Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfix
Self-Employed
 
Dataflow Analysis
Dataflow AnalysisDataflow Analysis
Dataflow Analysis
Eelco Visser
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
Rajendran
 
U2.linked list
U2.linked listU2.linked list
U2.linked list
Ssankett Negi
 
linked list
linked listlinked list
linked list
Abbott
 
Linked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory AllocationLinked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory Allocation
Prof Ansari
 
Linked lists
Linked listsLinked lists
Linked lists
Himadri Sen Gupta
 
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Peng Cheng
 
Register Allocation
Register AllocationRegister Allocation
Register Allocation
Eelco Visser
 
Stack, queue and hashing
Stack, queue and hashingStack, queue and hashing
Stack, queue and hashing
Dumindu Pahalawatta
 
Lab lect03 arith_control
Lab lect03 arith_controlLab lect03 arith_control
Lab lect03 arith_control
MPDS
 
LR parsing
LR parsingLR parsing
LR parsing
ichikaz3
 
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative Programmers
Chris
 
Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfix
Self-Employed
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
Rajendran
 
linked list
linked listlinked list
linked list
Abbott
 
Linked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory AllocationLinked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory Allocation
Prof Ansari
 
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Peng Cheng
 
Register Allocation
Register AllocationRegister Allocation
Register Allocation
Eelco Visser
 

Similar to Lisp tutorial (20)

LISP: Introduction To Lisp
LISP: Introduction To LispLISP: Introduction To Lisp
LISP: Introduction To Lisp
LISP Content
 
Advance LISP (Artificial Intelligence)
Advance LISP (Artificial Intelligence) Advance LISP (Artificial Intelligence)
Advance LISP (Artificial Intelligence)
wahab khan
 
Lecture 3 RE NFA DFA
Lecture 3   RE NFA DFA Lecture 3   RE NFA DFA
Lecture 3 RE NFA DFA
Rebaz Najeeb
 
Scheme language
Scheme languageScheme language
Scheme language
JITENDRA LENKA
 
(Ai lisp)
(Ai lisp)(Ai lisp)
(Ai lisp)
Ravi Rao
 
AutoDesk
AutoDeskAutoDesk
AutoDesk
SE3D
 
Lisp and scheme i
Lisp and scheme iLisp and scheme i
Lisp and scheme i
Luis Goldster
 
Full Stack Clojure
Full Stack ClojureFull Stack Clojure
Full Stack Clojure
Michiel Borkent
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
Vladimir Kostyukov
 
Ch8b
Ch8bCh8b
Ch8b
kinnarshah8888
 
Artificial Intelligence Lecture Slide-05
Artificial Intelligence Lecture Slide-05Artificial Intelligence Lecture Slide-05
Artificial Intelligence Lecture Slide-05
asmshafi1
 
Faster Python, FOSDEM
Faster Python, FOSDEMFaster Python, FOSDEM
Faster Python, FOSDEM
Victor Stinner
 
Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
Eric Bowman
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
Albert Bifet
 
cs201-list-stack-queue-linked-lists .ppt
cs201-list-stack-queue-linked-lists .pptcs201-list-stack-queue-linked-lists .ppt
cs201-list-stack-queue-linked-lists .ppt
4kdishinfo
 
cs201-list-stack-queue-linked-list (2).ppt
cs201-list-stack-queue-linked-list (2).pptcs201-list-stack-queue-linked-list (2).ppt
cs201-list-stack-queue-linked-list (2).ppt
4kdishinfo
 
Unit vii wp ppt
Unit vii wp pptUnit vii wp ppt
Unit vii wp ppt
Bhavsingh Maloth
 
Ch8a
Ch8aCh8a
Ch8a
kinnarshah8888
 
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaFunctional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Philip Schwarz
 
Seductions of Scala
Seductions of ScalaSeductions of Scala
Seductions of Scala
Dean Wampler
 
LISP: Introduction To Lisp
LISP: Introduction To LispLISP: Introduction To Lisp
LISP: Introduction To Lisp
LISP Content
 
Advance LISP (Artificial Intelligence)
Advance LISP (Artificial Intelligence) Advance LISP (Artificial Intelligence)
Advance LISP (Artificial Intelligence)
wahab khan
 
Lecture 3 RE NFA DFA
Lecture 3   RE NFA DFA Lecture 3   RE NFA DFA
Lecture 3 RE NFA DFA
Rebaz Najeeb
 
AutoDesk
AutoDeskAutoDesk
AutoDesk
SE3D
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
Vladimir Kostyukov
 
Artificial Intelligence Lecture Slide-05
Artificial Intelligence Lecture Slide-05Artificial Intelligence Lecture Slide-05
Artificial Intelligence Lecture Slide-05
asmshafi1
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
Albert Bifet
 
cs201-list-stack-queue-linked-lists .ppt
cs201-list-stack-queue-linked-lists .pptcs201-list-stack-queue-linked-lists .ppt
cs201-list-stack-queue-linked-lists .ppt
4kdishinfo
 
cs201-list-stack-queue-linked-list (2).ppt
cs201-list-stack-queue-linked-list (2).pptcs201-list-stack-queue-linked-list (2).ppt
cs201-list-stack-queue-linked-list (2).ppt
4kdishinfo
 
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaFunctional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Philip Schwarz
 
Seductions of Scala
Seductions of ScalaSeductions of Scala
Seductions of Scala
Dean Wampler
 
Ad

More from Nilt1234 (13)

INTRODUCTION TO LISP
INTRODUCTION TO LISPINTRODUCTION TO LISP
INTRODUCTION TO LISP
Nilt1234
 
Lec 09
Lec 09Lec 09
Lec 09
Nilt1234
 
relational algebra (joins)
relational algebra (joins)relational algebra (joins)
relational algebra (joins)
Nilt1234
 
relational algebra-(basics)
 relational algebra-(basics) relational algebra-(basics)
relational algebra-(basics)
Nilt1234
 
Artificial Intelligence
Artificial IntelligenceArtificial Intelligence
Artificial Intelligence
Nilt1234
 
Lec 17
Lec  17Lec  17
Lec 17
Nilt1234
 
Lec 06
Lec 06Lec 06
Lec 06
Nilt1234
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
Nilt1234
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
Nilt1234
 
introduction of Database
introduction of Databaseintroduction of Database
introduction of Database
Nilt1234
 
Database Architecture
Database Architecture Database Architecture
Database Architecture
Nilt1234
 
What is Artificial Intelligence
What is Artificial IntelligenceWhat is Artificial Intelligence
What is Artificial Intelligence
Nilt1234
 
Entity Relationship Diagaram
Entity Relationship DiagaramEntity Relationship Diagaram
Entity Relationship Diagaram
Nilt1234
 
INTRODUCTION TO LISP
INTRODUCTION TO LISPINTRODUCTION TO LISP
INTRODUCTION TO LISP
Nilt1234
 
relational algebra (joins)
relational algebra (joins)relational algebra (joins)
relational algebra (joins)
Nilt1234
 
relational algebra-(basics)
 relational algebra-(basics) relational algebra-(basics)
relational algebra-(basics)
Nilt1234
 
Artificial Intelligence
Artificial IntelligenceArtificial Intelligence
Artificial Intelligence
Nilt1234
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
Nilt1234
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
Nilt1234
 
introduction of Database
introduction of Databaseintroduction of Database
introduction of Database
Nilt1234
 
Database Architecture
Database Architecture Database Architecture
Database Architecture
Nilt1234
 
What is Artificial Intelligence
What is Artificial IntelligenceWhat is Artificial Intelligence
What is Artificial Intelligence
Nilt1234
 
Entity Relationship Diagaram
Entity Relationship DiagaramEntity Relationship Diagaram
Entity Relationship Diagaram
Nilt1234
 
Ad

Recently uploaded (20)

"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.
MCH
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.
MCH
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 

Lisp tutorial

  • 1. 1 CS 2740 Knowledge Representation M. Hauskrecht CS 2740 Knowledge Representation Lecture 2 Milos Hauskrecht [email protected] 5329 Sennott Square Introduction to LISP CS 2740 Knowledge Representation M. Hauskrecht LISP language LISP: LISt Processing language • An AI language developed in 1958 (J. McCarthy at MIT) • Special focus on symbolic processing and symbol manipulation – Linked list structures – Also programs, functions are represented as lists • At one point special LISP computers with basic LISP functions implemented directly on hardware were available (Symbolics Inc., 80s) LISP today: • Many AI programs now are written in C,C++, Java – List manipulation libraries are available
  • 2. 2 CS 2740 Knowledge Representation M. Hauskrecht LISP language LISP Competitors: • Prolog, Python • but LISP keeps its dominance among high level (AI) programming languages Current LISP: • Common Lisp • Scheme are the most widely-known general-purpose Lisp dialects Common LISP: • Interpreter and compiler • CLOS: object oriented programming CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial Syntax: • Prefix notation – Operator first, arguments follow – E.g. (+ 3 2) adds 3 and 2 A lot of parentheses • These define lists and also programs • Examples: – (a b c d) is a list of 4 elements (atoms) a,b,c,d – (defun factorial (num) (cond ((<= num 0) 1) (t (* (factorial (- num 1)) num)) ))
  • 3. 3 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: data types Basic data types: • Symbols – a – john – 34 • Lists – ( ) – (a) – (a john 34) – (lambda (arg) (* arg arg)) CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial For each symbol lisp attempts to find its value > (setq a 10) ;; sets a value of symbol a to 10 10 > a ;; returns the value of a 10 Special symbols: > t ;; true T > nil ;; nil stands for false or NIL > ( ) ;; an empty list NIL
  • 4. 4 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial Lists represent function calls as well as basic data structures > (factorial 3) 6 > (+ 2 4) 6 > (setq a ‘(john peter 34)) ;; quote means: do not eval the argument (john peter 34) > (setq a ‘((john 1) (peter 2))) ((john 1) (peter 2)) CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: lists List representation: • A singly linked list > (setq a ‘(john peter)) (john peter) > (car a) john > (cdr a) (peter) car cdr
  • 5. 5 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: list List building functions > (cons ‘b nil) ;; quote means: do not eval the argument (b) > (setq a (cons ‘b (cons ‘c nil)) ;; setq a is a shorthand for set ‘a (b c) > (setq v (list ‘john 34 25)) (john 34 25) > (setq v (list a 34 25)) ((b c) 34 25) > (append ‘(1 2) ‘(2 3)) (1 2 2 3) CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial List copying > (setq foo (list 'a 'b 'c)) (a b c) > (setq bar (cons 'x (cdr foo))) (x b c) > foo (a b c) ;; (cdr foo) makes a copy of the remaining list before cons > bar (x b c) • Car and cdr operations are nondestructive.
  • 6. 6 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: lists > (setq bar ‘(a b c)) (a b c) > (setq foo (cdr bar)) (b c) > (rplaca foo ‘u) ;; replaces car component of foo (destructive op) (u c) > foo (u c) > bar (a u c) > (rplacd foo ‘(v)) ;; replaces cdr component of foo (destructive) (u v) > bar (a u v) CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial The same effect as with rplaca and rplacd can be achieved with setf > (setq bar ‘(a b c)) (a b c) > (setq foo (cdr bar)) (b c) > (setf (cadr bar) ‘u) u > bar (a u c) > foo (u c)
  • 7. 7 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial Evaluation rules: • A symbol value is sought and substituted • A quoted value is kept untouched > (setq a 12) 12 > (setq b (+ a 4)) 16 > (setq b ‘(+ a 4)) (+ a 4) > (eval b) ;; explicit evaluation call 16 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: functions and predicates Some useful functions and predicates: > (setq a ‘(1 2 3 4 5)) (1 2 3 4 5) > (length a) ;; gives the list length of the argument 5 > (atom ‘a) ;; checks if the argument is an atom T > (atom a) NIL > (listp ‘a) ;; checks if the argument is a list NIL > (listp a) T
  • 8. 8 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: function definition Definition of a function (defun <f-name> <parameter-list> <body>) >(defun square (x) (* x x)) SQUARE >(square 2) 4 >(square (square 2)) 16 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial Definition of a function (defun <f-name> <parameter-list> <body>) <body> can be a sequence of function calls, the function returns the value of the last call in the sequence > (defun foo (a) (setq b (+ a 1)) (setq c (+ a 2)) c) FOO > (foo 2) 4
  • 9. 9 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: conditionals Cond statement: sequentially tests conditions, the call associated with the first true condition is executed > (defun abs (a) (cond ((> a 0) a) (t (- a)))) ABS > (abs 2) 2 > (abs -3) 3 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial if statement: (if <test> <then> <else>) > (defun abs (a) (if (> a 0) a (- a))) ABS > (abs 2) 2 > (abs -3) 3
  • 10. 10 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: equality 4 equality predicates: =, equal, eq, eql > (= 2 4/2) ;; used for numerical values only T > (setf a '(1 2 3 4)) (1 2 3 4) >(setf b '(1 2 3 4)) (1 2 3 4) >(setf c b) (1 2 3 4) > (equal a b) ;; equal is true if the two objects are isomorphic T > (equal c b) T CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: equalities >(eq a b) ;; eq is true if the two arguments point to the same object NIL >(eq b c) T
  • 11. 11 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: nil Nil represents False and an empty list > (null nil) ;; tests if the argument is NIL T > (null ( )) T > (null ‘(a b)) NIL > (not ‘(a b)) NIL CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: functions Logical operators: and, or > (and NIL T) NIL > (and T 2 3) 3 > (or nil (= 5 4)) NIL > (or nil 5) 5
  • 12. 12 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: recursion Recursive function definitions are very common in LISP > (defun factorial (num) (cond ((<= num 0) 1) (t (* (factorial (- num 1)) num)) )) FACTORIAL > (factorial 4) 24 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: recursion Recursive function definitions are very common in LISP > (defun check_lists (lis) (cond ((null lis) nil) (t (cons (listp (car lis)) (check_lists (cdr lis)))))) CHECK_LISTS > (check_lists (list ‘a ‘(1 2) 3 ‘(a b c) ‘(a))) (NIL T NIL T T)
  • 13. 13 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: local and global variables > (setq a 12) 12 > (defun foo (n) (setq a 14) (+ n 2)) FOO > a 12 > (foo 3) 5 > a 14 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: local variables Defining local variables with let > (setq a 7) ;store a number as the value of a symbol 7 > a ;take the value of a symbol 7 > (let ((a 1)) a) ;binds the value of a symbol temporarily to 6 1 > a ;the value is 7 again once the let is finished 7 > b ;try to take the value of a symbol which has no value Error: Attempt to take the value of the unbound symbol B
  • 14. 14 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: local variables Defining local variables with let and let* > (let ((a 5) ;; binds vars to values locally (b 4)) (+ a b)) 9 > (let* ((a 5) ;; binds vars sequentially (b (+ a 2)) (+ a b)) 12 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: functions revisited Standard function – all parameters defined (defun fact (x) (if (> x 0) (* x (fact (- x 1))) 1)) But it is possible to define functions: • with variable number of parameters, • optional parameters and • keyword-based parameters
  • 15. 15 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: functions revisited Functions with optional parameters > (defun bar (x &optional y) (if y x 0)) BAR > (defun baaz (&optional (x 3) (z 10)) (+ x z)) BAAZ > (bar 5) 0 > (bar 5 t) 5 > (baaz) 13 > (baaz 5 6) 11 > (baaz 5) 15 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: functions revisited Functions with variable number of parameters > (defun foo (x &rest y) y) ;; all but the first parameters are put ;; into a list FOO > (foo 3) NIL > (foo 1 2 3) (2 3) > (foo 1 2 3 4 5) (2 3 4 5)
  • 16. 16 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: functions revisited Functions with ‘keyword’ parameters > (defun foo (&key x y) (cons x y)) FOO > (foo :x 5 :y ‘(3)) (5 3) > (foo :y ‘(3) :x 5) (5 3) > (foo :y 3) (NIL 3) > (foo) (NIL) CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: arrays List is a basic structure; but arrays and structures are supported > (setf a (make-array ‘(3 2)) ;; make a 3 by 2 array #2a((NIL NIL) (NIL NIL) (NIL NIL)) > (aref a 1 1) NIL > (setf (aref a 1 1) 2) 2 > (aref a 1 1) 2
  • 17. 17 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: structures >(defstruct weather temperature rain pressure) WEATHER > (setf a (make-weather)) ;; make a structure #s(WEATHER :TEMPERATURE NIL :RAIN NIL :PRESSURE NIL) > (setf a (make-weather :temperature 35)) #s(WEATHER :TEMPERATURE 35 :RAIN NIL :PRESSURE NIL) > (weather-temperature a) ;; access a field 35 > (weather-rain a) NIL > (setf (weather-rain a) T) ;; set the value of a field T > (weather-rain a) T CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: iterations Many ways to define iterations Commands: • loop • dolist • dotimes • do, do* Also we can write compactly the code for repeated application of function to elements of the list: • mapc, mapcar
  • 18. 18 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: iterations Iterations: loop > (setq a 4) 4 > (loop (setq a (+ a 1)) (when (> a 7) (return a))) ;; return exists the loop 8 > (loop (setq a (- a 1)) (when (< a 3) (return))) NIL CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: iterations Iterations: dolist > (dolist (x '(1 2 3 4)) (print x)) 1 2 3 4 NIL ;; NIL is returned by dolist >
  • 19. 19 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: iterations Iterations: dotimes > (dotimes (i 4) (print i)) ;; starts from 0 and continues till limit 4 0 1 2 3 4 NIL ;; returns NIL CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: iterations Iterations: do > (do ((x 1 (+ x 1)) ;; variable, initial value, next cycle update (y 1 (* y 2))) ;; the same ((> x 5) y) ;; end condition, value do returns (print (list x y)) ;; body of do – a sequence of operations (print ‘next)) (1 1) NEXT (2 2) NEXT (3 4) NEXT (4 8) NEXT (5 16) NEXT 32
  • 20. 20 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: iterations Iterations: do * > (do* ((x 1 (+ x 1)) ;; variable, initial value, next cycle update (y 1 (* x 2))) ;; <<< --- update based on x ((> x 5) y) ;; end condition, value do returns (print (list x y)) ;; body of do – a sequence of operations (print ‘next)) (1 1) NEXT (2 4) NEXT (3 6) NEXT (4 8) NEXT (5 10) NEXT 12 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: mapcar Repeated application of a function to elements of the list > (mapcar #’oddp ‘(1 2 3 4 5)) ;; named function (T NIL T NIL T) > (mapcar #’(lambda(x) (* x x)) ‘(1 2 3 4 5)) ;;temp function (1 4 9 16 25)
  • 21. 21 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial Evals and function calls • A piece of code can be built, manipulated as data • What if we want to execute it? > (setq b ‘(+ a 4)) (+ a 4) > (eval b) ;; explicit evaluation call 16 > (funcall #’+ 2 4) ;; calls a function with args 6 > (apply #’+ 2 ‘(5 6)) ;; calls a function with args (last args as a list) 13 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: input/output You can input/output data to: • standard input/output, • string or • file A number of functions supported by the Lisp: • (read) ;; reads the input from the standard input • (print ‘a) ;; prints to the standard output • (scanf …) (printf …) (format …) for formatted input and output • (open ..) (close ..) for opening and closing the files • (load ..) reads and executes the file
  • 22. 22 CS 2740 Knowledge Representation M. Hauskrecht LISP tutorial: program calls Assume you have your lisp code ready in the .lisp file This is how you load it (load "~/private/lsp/file-to-load.lisp") … and you can call another load from it as well CS 2740 Knowledge Representation M. Hauskrecht Running LISP for CS Students • Remotely login via ssh to elements.cs.pitt.edu • LISP is installed in the following directory: /usr/local/contrib/cmucl-19d/ • You can run lisp from linux by typing /usr/local/contrib/cmucl- 19d/bin/lisp – You may want to provide a path to the lisp directory so that the executable is seen from anywhere – To do this, edit your .cshrc.custom file under your home directory and add the following line: set path = ($path /usr/local/contrib/cmucl-19d/bin) • Use the command (quit) to quit LISP
  • 23. 23 CS 2740 Knowledge Representation M. Hauskrecht Running LISP for Non-CS Students • Remotely login via ssh to unixs.cis.pitt.edu • LISP is installed in the following directory: /usr/pitt/franz-lisp/ • You can run lisp from unix by typing: /usr/pitt/franz-lisp/mlisp – You may want to provide a path to the lisp directory so that the executable is seen from anywhere – To do this, edit your .cshrc file under your home directory and add the following line: set path = ($path /usr/pitt/franz-lisp) • If .cshrc is read-only, then add write permission with the command: chmod u+w .cshrc • Use the command (exit) to quit LISP