CMSC 671 - Fall '03 LECTURE NOTES FOR 9/3/03 Prof. Marie desJardins 4:00 - 4:15 Course overview 4:15 - 4:50 Introduction to AI 4:50 - 5:15 Lisp mini-tutorial (slides and Fibonacci example) BASIC LISP PROGRAMMING AND DEBUGGING - FIBONACCI SEQUENCE EXAMPLE [for Marie's laptop only - not relevant for students reading these notes!] start MS-DOS prompt cd c:\windows\clisp-2.27 lisp.exe -M lispinit.mem -B . (cd "c:\\my documents\\umbc\\671\\") - create and load fib.lisp in this directory -- FIBONACCI SEQUENCE 0 1 1 2 3 5 8 13 21 34 55 ... (each Fibonacci number is the sum of the previous two Fibonacci numbers) Fib (0) = 0 Fib (1) = 1 Fib (n) = Fib (n-1) + Fib (n-2), n in Integers, n > 1 -- VERSION 1 (just plain wrong) (defun fib (n) (+ n (decf n))) -- VERSION 2 (at least it's recursive... infinitely recursive!) (defun fib (n) (+ n (fib (decf n)))) -- VERSION 3 (recursion is getting better... how about a base case?? try tracing the function!) (defun fib (n) (+ (fib (decf n)) (fib (decf n)))) -- VERSION 4 (now we've got a base case, but there are these cond and decf problem that need to be fixed) (defun fib (n) (cond ((eql n 0) 0) (eql n 1) 1 (t (+ (fib (decf n)) (fib (decf (decf n))))))) -- VERSION 5 (pretty good, but how about some documentation and error checking?) (defun fib (n) (cond ((eql n 0) 0) ((eql n 1) 1) (t (+ (fib (- n 1)) (fib (- n 2)))))) -- VERSION 6 (perfect! correct, indented, elegant, commented, and error checked) (defun fib (n) "Computes the nth Fibonacci number" (cond ((or (not (numberp n)) (< n 0)) ;; error case (error "~s is not a legal value for n!~&" n)) ((eql n 0) 0) ;; base case ((eql n 1) 1) ;; base case (t (+ (fib (- n 1)) ;; recurse and compute (fib (- n 2)))) )) -- LET'S TRY IT! (fib -1) (fib '(list)) (fib 0) (fib 1) (fib 2) (fib 4) (loop for i from 0 to 10 do collect (fib i))