; 1.37 (cont-frac) and 1.38 (special usage of cont-frac)
;
; n and d are functions as seen in the
; example usage:
;
; (cont-frac (lambda (x) 1) (lambda (x) 1) k)
;
; where k is the number of terms

(define (cont-frac n d k)
  (define (cf counter)
    (cond ((= k counter) (/ (n counter) (d counter)))
          (else (/ (n k) (+ (d k) (cf (+ counter 1)))))))
  (cf 1))

(define (cont-frac-iter n d k)
  (define (cf result k)
    (cond ((= k 1) (/ (n 1) (+ (d 1) result)))
          (else (cf (/ (n k) (+ (d k) result)) (- k 1)))))
  (cf 0 k))

(define (e-2term n)
  (cond ((= (remainder n 3) 2) (* 2 (/ (+ n 1) 3)))
        (else 1)))

; 1.42 (compose) and 1.43 (repeated)

(define (square x) (* x x))
(define (1+ x) (+ x 1))
; > ((compose square 1+) 3)
; 16
(define (compose f g)
  (lambda (x)
    (f (g x))))


; ((repeated square 4) 2) --> 65536
; ((repeated square 0) 4) --> 4
(define (repeated f n) ; apply function f n times ((repeated square 4) 2) --> 65536
  (lambda (x)
    (cond ((= n 0) x)
          (else ((compose (repeated f (- n 1)) f) x)))))