;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; U. C. Berkeley ;; ;; EECS Computer Science Division ;; ;; CS3 Lecture 09 Answers ;; ;; (Tail Recursion) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Normal way we've seen of writing sum-0-to-n ;; (using embedded recursion) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (sum-0-to-n n) (if (= n 0) 0 (+ n (sum-0-to-n (- n 1))))) (model (sum-0-to-n 3)) ;; ==> 6 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Tail recursive way to write sum-0-to-n ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (sum-0-to-n-tail n) (sum-0-to-n-tail-helper n 0)) (define (sum-0-to-n-tail-helper n sum-so-far) (if (= n 0) sum-so-far (sum-0-to-n-tail-helper (- n 1) (+ sum-so-far n)))) (model (sum-0-to-n-tail 3)) ;; ==> 6 ;;;;;;;;;;;;;;;;;;;;; ;; my-count embedded ;;;;;;;;;;;;;;;;;;;;; (define (my-count s) (if (empty? s) 0 (+ 1 (my-count (bf s))))) (model (my-count '(cs3 is the best class))) ;; ==> 5 ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; my-count tail recursive ;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (my-count-tail s) (mct-helper s 0)) (define (mct-helper s count-so-far) (if (empty? s) count-so-far (mct-helper (bf s) (+ 1 count-so-far)))) (model (my-count-tail '(cs3 is the best class))) ;; ==> 5 ;;;;;;;;;;;;;;;;;;;;;; ;; count-even-and-odds ;;;;;;;;;;;;;;;;;;;;;; (define (count-even-and-odds s) (ceao-helper s 0 0)) (define (ceao-helper s num-evens num-odds) (cond ((empty? s) (se num-evens num-odds)) ((even? (first s)) (ceao-helper (bf s) (+ 1 num-evens) num-odds)) (else (ceao-helper (bf s) num-evens (+ 1 num-odds))))) (count-even-and-odds '(1 2 3 0 -4 8 5)) ;; ==> (4 3) ;;;;;;;;;;;;;;;;; ;; all-increasing ;;;;;;;;;;;;;;;;; (define (all-increasing? s) (ai-helper? (bf s) (first s))) (define (ai-helper? s most-recent) (cond ((empty? s) #t) ((> (first s) most-recent) (ai-helper? (bf s) (first s))) (else #f))) (all-increasing? '(-50 1 2 3 5)) ;; ==> #t (all-increasing? '(1 2 3 0)) ;; ==> #f ;;;;;;;;;;;;;;;;;;;;; ;; longest-win-streak ;;;;;;;;;;;;;;;;;;;;; (define (longest-win-streak s) (lws-helper s 0 0)) (define (lws-helper s cur-strk max-strk) (cond ((empty? s) max-strk) ((equal? (first s) 'l) (lws-helper (bf s) 0 max-strk)) (else (lws-helper (bf s) (+ 1 cur-strk) (if (= cur-strk max-strk) (+ max-strk 1) max-strk))))) (longest-win-streak '(l l l l)) ;; ==> 0 (longest-win-streak '(l w w w l w w l l l l w)) ;; ==> 3