DEV Community

Cover image for SICP Chapter 1:3:1
Brian.Mumo
Brian.Mumo

Posted on

SICP Chapter 1:3:1

Procedures as Arguments
Its a pseudo-revamp or alternative approach to the examples and some exercises in the book

Addition via linear recursion

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

Approach 2 of addition via linear recursion
(define (sum-int a b)
(define (inc n )(+ n 1))
(if (> a b)
0
(+ a (sum-int (inc a) b))))

Addition of cubes via linear recursion
(define (sum-cubes a b)
(define (cube z)(* z z z ))
(if (> a b)
0
(+ (cube a)(sum-cubes(+ a 1) b))))

Approach 2 of addition of cubes via linear recursion

(define (sum-cubes a b)
(define (cube z)(* z z z))
(define (inc n)(+ n 1))
(if (> a b)
0
(+ (cube a)(sum-cubes (inc a) b))))

Approach of sequential sum

(define (sum-pi a b)
(if (= a 0)
"null"
(if (> a b)
0
(+ (/ 1.0 (* a(+ a 2)))(sum-pi (+ a 4) b)))))

Approach of exercise 1.30 Additions via iteration

(define (sum a b)
(define (next n)(+ n 1))
(define (iter a result)
(if (> a b)
result
(iter (next a)(+ result (next a)))))
(iter a 0))

Approach to exercise 1.31 Factorial via iteration

(define (Product a b)
(define (next n)(+ n 1))
(define (iter a result)
(if (> a b)
result
(iter (next a)(* result (next a)))))
(iter a 0))

Top comments (0)