180 likes | 299 Views
Common Lisp!. John Paxton Montana State University Summer 2003. Montana Facts. State Animal: Grizzly Bear. Montana Facts. State Flag. Recursion.
E N D
Common Lisp! John Paxton Montana State University Summer 2003
Montana Facts • State Animal: Grizzly Bear
Montana Facts • State Flag
Recursion • Tail recursion occurs if the final answer is known when the base case is hit. Most Lisp compilers can detect tail recursion and can translate the tail recursion into an equivalent looping structure.
Rest Recursion (defun my-reverse (alist) (if (null alist) nil (append (my-reverse (rest alist)) (list (first alist))) ) )
Rest Recursion > (my-reverse '(1 2 3)) (3 2 1) > (trace my-reverse)
Rest Recursion > (my-reverse '(1 2 3)) 1. Trace: (MY-REVERSE '(1 2 3)) 2. Trace: (MY-REVERSE '(2 3)) 3. Trace: (MY-REVERSE '(3)) 4. Trace: (MY-REVERSE 'NIL) 4. Trace: MY-REVERSE ==> NIL 3. Trace: MY-REVERSE ==> (3) 2. Trace: MY-REVERSE ==> (3 2) 1. Trace: MY-REVERSE ==> (3 2 1) (3 2 1)
Tail Recursive Version (defun my-reverse (alist &optional (result nil)) (if (null alist) result (my-reverse (rest alist) (cons (first alist) result) ) )
Tail Recursive Version > (my-reverse '(1 2 3)) (3 2 1) > (trace my-reverse) > (my-reverse ‘(1 2 3))
Tail Recursive Version 1. Trace: (MY-REVERSE '(1 2 3)) 2. Trace: (MY-REVERSE '(2 3) '(1)) 3. Trace: (MY-REVERSE '(3) '(2 1)) 4. Trace: (MY-REVERSE 'NIL '(3 2 1)) 4. Trace: MY-REVERSE ==> (3 2 1) 3. Trace: MY-REVERSE ==> (3 2 1) 2. Trace: MY-REVERSE ==> (3 2 1) 1. Trace: MY-REVERSE ==> (3 2 1) (3 2 1)
First/Rest Recursion (defun reverse-all (alist) (cond ((null alist) nil) ((atom alist) alist) (t (append (reverse-all (rest alist)) (list (reverse-all (first alist))))) ) )
First/Rest Recursion > (reverse-all '(((1) (2 3) 4))) ((4 (3 2) (1)))
Question • Trace (reverse-all ‘(1 ((2) 3))) by hand.
Optional Parameters > (defun add (n &optional (m 1)) (+ n m)) ADD > (add 10) 11 > (add 10 2) 12
Rest Parameters (defun example (&rest elements) (length elements) ) EXAMPLE > (example) > (example 1 2 3 4) > (example ‘(1 2))
Keyword Parameters (defun add (&key (n1 0) (n2 0)) (+ n1 n2)) ADD > (add) > (add :n1 7 :n2 3) > (add :n2 3)
Questions • Develop a recursive function called my-count that computes the number of times than an atomic key appears as a top-level element in a list. For example, (my-count 1 ‘(1 2 (1 3) 1)) should return a 2. Trace the function. • Repeat the above question but now make the function tail recursive. Trace the function.
Questions • Change the function my-count so that it counts all occurrences of the key. For example, (my-count 1 ‘(1 2 (1 3) 1)) should return a 3. Trace the function. • Define my-nthcdr, a function that uses a keyword parameter with a default value of 1. Do not use nthcdr in the function body!