;; Given a nonnegative integer n, the following procedure f computes ;; (sum of all the digits of n at even positions) ;; + 2 * (sum of all the digits of n at odd positions) ;; Note that we count digit position right-to-left starting from position 0. ;; ;; For example, ;; f(32) = 2 + 2*3 = 8 ;; f(3214) = (4+2) + 2*(1+3) = 14 ;; ;; Note that the first three versions of f below generate recursive processes. ;; This is true even when the second version of f has a helper function! ;; First Version ;; MUTUALLY RECURSIVE PROCEDURES (define f (lambda (n) (if (= n 0) 0 (+ (remainder n 10) (g (quotient n 10)))))) (define g (lambda (n) (if (= n 0) 0 (+ (* 2 (remainder n 10)) (f (quotient n 10)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Second Version (define f (lambda (n) (define f-helper (lambda (n even-pos?) (if (= n 0) 0 (if even-pos? (+ (remainder n 10) (f-helper (quotient n 10) (not even-pos?))) (+ (* 2 (remainder n 10)) (f-helper (quotient n 10) (not even-pos?))))))) (f-helper n #t))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Third Version ;; Process 2 digits at a time, recursively. (define f (lambda (n) (if (= n 0) 0 (+ (f (quotient n 100)) (* 2 (quotient (remainder n 100) 10)) (remainder n 10))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Fourth Version ;; Process 2 digits at a time, iteratively. (define f (lambda (n) (define f-helper (lambda (result n) (if (= n 0) result (f-helper (+ result (* 2 (quotient (remainder n 100) 10)) (remainder n 10)) (quotient n 100))))) (f-helper 0 n)))