(define function-add (lambda (f g x) (+ (f x) (g x)))) (define function-subtract (lambda (f g x) (- (f x) (g x)))) (define function-multiply (lambda (f g x) (* (f x) (g x)))) (define function-divide (lambda (f g x) (/ (f x) (g x)))) (define function-compose (lambda (f g x) (f (g x)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 'n' is a positive integer with decimal representation d_k d_{k-1}... d_1 d_0, ;; 'f' takes two integral arguments, the first is a decimal digit, the second is ;; the digit position (counting from the right and starting from 0) ;; 'g' is an associative binary operator, g of the empty set equals 'base-value' ;; ;; This procedure computes ;; g ( f(d_k, k), ( g(f_{k-1}, k-1), ... g( f(d_1, 1), g(f(d_0), 0 ))...) ;; (define digits-processor (lambda (f g base-value n) (define helper (lambda (n position result) (if (= n 0) result (helper (quotient n 10) (+ position 1) (g (f (remainder n 10) position) result))))) (helper n 0 base-value))) (define number-of-6s (lambda (n) (digits-processor (lambda (d p) (if (= d 6) 1 0)) + 0 n))) (define sum-of-digits (lambda (n) (digits-processor (lambda (d p) d) + 0 n))) (define alternating-plus-minus-of-digits (lambda (n) (digits-processor (lambda (d p) (if (even? p) d (- d))) + 0 n))) (define alternating-once-twice-of-digits (lambda (n) (digits-processor (lambda (d p) (if (even? p) d (+ d d))) + 0 n))) (define reverse (lambda (n) (digits-processor (lambda (d p) d) (lambda (a b) (+ a (* 10 b))) 0 n))) (define even-digits-number-of (lambda (n) (digits-processor (lambda (d p) (if (or (odd? p) (= d 0)) 0 (* d (expt 10 (/ p 2))))) + 0 n))) (define odd-digits-number-of (lambda (n) (digits-processor (lambda (d p) (if (or (even? p) (= d 0)) 0 (* d (expt 10 (quotient p 2))))) + 0 n))) (define contains-any-6? (lambda (n) (digits-processor (lambda (d p) (= d 6)) (lambda (a b) (or a b)) #f n))) (define all-digits-odd? (lambda (n) (digits-processor (lambda (d p) (odd? d)) (lambda (a b) (and a b)) #t n)))