CS 227 lecture -*- Outline -*- For next year: need some examples that does work AFTER the recursive call, that shows that the recursion "comes back". Point out how this works: stacks, variable creation, etc. Should also put this kind of thing in tracing lecture. * recursion ** problem we can now write procedures that do different things with their output, but we can't yet repeat something any number of times, ** example find the last item in a list ---------- task: return last item of list (assume not empty) examples? plan: if list has 1 item return first item if list has 2 items return second item ... ----------- ask them for examples can translate the plan to code but shows the problem ---------- (define last-item (lambda (lst) ; REQUIRES: lst is not empty (cond ((null? (cdr lst)) (car lst)) ((null? (cddr lst)) (cadr lst)) ((null? (cddr lst)) (caddr lst)) ; ... ))) ---------- this plan is unworkable! what are the problems? can't write it all down lots of redundancy how did we eliminate writing the same thing twice before? used helping procedures but what other procedures have we got that can help? none so this procedure will have to help itself such procedures are called recursive ------------- new plan: if list has 1 item return first item otherwise return last item of the cdr of list ------------- to code this use last-item as a helping procedure ------------- (define last-item (lambda (lst) ; REQUIRES: lst is not empty (cond ((null? (cdr lst)) (car lst)) (else (last-item (cdr lst)))))) ------------- try it! show how it works by equations on examples '(1 2 3) why does it stop? stops on length 1 list by inspection of code length of non-empty list is always a positive number each recursive call decreases the length can't both decrease and remain positive forever why does it work? by induction on structure of non-empty lists (do this both forwards and backwards) ---------- a non-empty list is either: (cons x '()) or (cons x tail) where tail is a non-empty list ---------- last element in 2nd case is the last element of the tail = (cdr lst) how did we invent the plan? by looking at the structure of non-empty lists one case for base, one for induction same trick works for lists: ---------- a list is either: '() or (cons x tail) where tail is a list ---------- ** more examples append not-member? remove-1st double (a b) ==> (a a b b)