summaryrefslogtreecommitdiff
path: root/coding-exercises/1/32.rkt
blob: 21a557c12452f9ca3131df976e136c5b91f22c85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#lang racket

(define (accumulate combiner null-value term a next b)
  (define (iter a result)
    (if (> a b)
      result
      (iter 
        (next a)
        (combiner
          (term a)
          result))))
  (iter null-value a))

(define (accumulate combiner null-value term a next b)
  (if (> a b)
    null-value
    (combiner 
      (term a)
      (accumulate 
        combiner 
        null-value 
        term (next a) next b)))) 


(define (sum term a next b)
  (accumulate
    (lambda (x y) (+ x y))
    0
    term a next b))

(define (product term a next b)
  (accumulate
    (lambda (x y) (* x y))
    1
    term a next b))

(sum id 0 inc 8)
(product id 1 inc 3)