Zapiski #3 srečanja programerskega bralnega krožka SICP

Teme

Funkcije višjega reda

Vaje

1.29 Simpsonovo pravilo

(define(cube x)
  (* x x x))

(define(sum-integers a b)
  (if ( > a b)
      0
      (+ a (sum-integers (+ a 1) b))))

(define(sum-cubes a b)
  (if (> a b)
      0
      (+ (cube a) (sum-cubes(+ a 1) b))))


(define (sum term a next b)
  (if (> a b)
      0
      (+ (term a)
         (sum term (next a) next b))))

(define (integral f a b dx)
  (define (add-dx x) (+ x dx))
  (* (sum f (+ a (/ dx 2.0)) add-dx b)
     dx))

(define (simpson f a b n)
  (define h (/ (- b a) n))
  (define (add-hh a) (+ a h h))
  (* (+ (- (f a))
        (* 2 (sum f a add-hh b))
        (* 4 (sum f (+ a h) add-hh b))
        (- (f b)))
     (/ h 3.0)))


(list (simpson cube 1 2 100)
      (simpson cube 1 2 1000))
3.7500000000000004 3.75

1.30 linearen sum

Rekurzivne procedure:

(define (sum term a next b)
  (if (> a b)
      0
      (+ (term a)
         (sum term (next a) next b))))

(define (cube n) (* n n n))
(define (inc n) (+ n 1))

(define (sum-cubes a b)
  (sum cube a inc b))

(sum-cubes 1 10)
3025

Iterativne procedure:

(define (sum-iter term a next b)
  (define (iter a result)
    (if (> a b)
       result
       (iter (next a) (+ result (term a)))))
  (iter a 0))

(define (cube n) (* n n n))
(define (inc n) (+ n 1))

(define (sum-cubes-iter a b)
  (sum-iter cube a inc b))

(sum-cubes-iter 1 10)
3025

1.31 Produkt višjega reda

(define (prod-iter term a next b)
  (define (iter a result)
    (if (> a b)
       result
       (iter (next a) (* result (term a)))))
  (iter a 0))

(define (piblizek n)
  (define (stevec n)
    (+ n 2))
  (* 4 (/ (prod-iter (lambda (n) (* (- n 1) (+ n 1)))
                     3
                     stevec
                     n)
          (prod-iter (lambda (n) (* n n))
                     3
                     stevec
                     n))))

(piblizek 10)

TODO popravi!