Notes LISP 2

Math 61 -- D. C. Smolarski, S.J.
Santa Clara University, Department of Mathematics and Computer Science

[Return to Math 61 Homepage | Return to Notes Listing Page]

Contents


Arithmetic Example

Arithmetic Function
	(defun exp (x y)
           (cond ((zerop y) 1)
                 ((* x (exp x (1- y))))))

	>(exp 2 3)
	8

Sample Session

Script started on Wed Apr  7 21:11:37 1999
math 21: cat foo.lsp
(defun for (a)
      (prog ()
	    loop (print (car a))
	         (setq a (cdr a))
		 (cond ((not (null a)) (go loop)))))
(defun rev (x)
      (cond ((null (cdr x)) (print (car x)))
	    ((prog () (rev (cdr x))
		      (print (car x))))))
math 22: lisp
AKCL (Austin Kyoto Common Lisp)  Version(1.619) Thu Oct  7 15:46:49 PDT 1993
Contains Enhancements by W. Schelter

>(+ 1 2)
3

>(setq a 2)
2

>(setq b '(a 2 3))
(A 2 3)

>(car b)
A

>(cdr b)
(2 3)

>(cons '+ (cdr b))
(+ 2 3)

>(setq c (cons '+ (cdr b)))
(+ 2 3)

>c
(+ 2 3)

>(eval c)
5

>(load "foo.lsp")
Loading foo.lsp
Finished loading foo.lsp
T

>(setq d '(1 2 3 4 5 6 7))
(1 2 3 4 5 6 7)

>d
(1 2 3 4 5 6 7)

>(rev d)

7 
6 
5 
4 
3 
2 
1 
NIL

>(for d)

1 
2 
3 
4 
5 
6 
7 
NIL

>(bye)
Bye.
math 24: exit
math 25: 
script done on Wed Apr  7 21:13:45 1999

More LISP Examples

LISP enables us to do more with recursive programming and to think in terms of lists as basic data structures.

Some books refer to "pure" LISP, i.e., using just the basic functions. Let's look at some standard functions defined in terms of more elementary functions recursively.

LENGTH => number

	(defun length (x)
		(cond ((null x) 0)
			 ((1+ (length (cdr x)))) ))

MEMBER => T/NIL

	(defun member (x y)
		(cond ((null y) nil)
			 ((equal x (car y)) T)
			 ((member x (cdr y))) ))

APPEND => list

	(defun append (x y)
		(cond ((null x) y)
			 ((cons (car x) (append (cdr x) y))) ))

This page is maintained by Dennis C. Smolarski, S.J.
© Copyright 1998, 1999 Dennis C. Smolarski, SJ, All rights reserved.
Last changed: 7 April 1999.