; Recursion with lists ; Note: exercises 4-8 should be turned in with comments and test cases ; ; We develop recursive functions for problems by exploiting the following ; two properties: ; ; 1) There is a trivial case that we can easily answer ; ; 2) every other case can be reduced to a smaller case ; ; example: sum (from the reading), finds the sum of a list of numbers ; ; 1) simple case: (sum '()) --> 0 ; ; 2) reduction to a smaller problem: ; (sum '(8 13 21 34)) --> (+ 8 (sum '(13 21 34))) ; (sum ls) --> (+ (car ls) (sum (cdr ls))) ; ; use these to write the procedure called sum (define sum (lambda (ls) (if (null? ls) 0 (+ (car ls) (sum (cdr ls)))))) ; trace through of sum ; (sum '(1 2 3)) ; (+ 1 (sum '(2 3))) ; (+ 1 (+ 2 (sum '(3)))) ; (+ 1 (+ 2 (+ 3 (sum '())))) ; (+ 1 (+ 2 (+ 3 0))) ; (+ 1 (+ 2 3)) ; (+ 1 5) ; 6 ; write DOUBLE which takes a list of numbers and returns a list with ; each element doubled ; 1) (double '()) --> '() ; 2) (double '(1 3 7)) --> '(2 6 14) ; --> (cons (* 2 (car ls)) (double (cdr ls))) ; --> (cons (* 2 1) (double '(3 7))) (define double (lambda (ls) (if (null? ls) '() (cons (* 2 (car ls)) (double (cdr ls)))))) ; write a procedure called ALL-EVEN? which takes in a list of numbers ; and returns #t if all the elements are even, and #f if not ; note I put a ? at the end of the name to signify that this returns a boolean value ; 1) (all-even? '()) --> #t ; ; 2) (all-even? '(2 4 7)) --> (all-even? '(4 7)) ; (all-even? '(3 4 6)) --> #f (define all-even? (lambda (ls) (if (null? ls) #t (if (odd? (car ls)) #f (all-even? (cdr ls)))))) ; Here is another way to do this, using OR and AND instead of IF (define all-even? (lambda (ls) (or (null? ls) (and (even? (car ls)) (all-even? (cdr ls)))))) ; When you are writing procedures remember the three uses for parenthesis ; in Scheme ; 1) to call a procedure ; (PROCEDURE ARGUMENTS) ; example: (+ 1 (sum (cdr ls))) ; ; 2) to make a new list (useful when you are testing your procedures) ; '(LIST-ELEMENTS) ; example: '(a b c) ; ; 3) for special built in procedures like ; ; (lambda (VARIBLE-NAMES) EXPRESSION) ; ; (cond ; ( ) ; .... ; ( ))