]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/utils.rkt
Lazy version of evaluator and tests.
[sicp.git] / src / sicp / utils.rkt
1 #lang racket
2
3 (define (square x) (* x x))
4
5 (define (abs x)
6   (if (< x 0) (- x) x))
7
8 (define (divides? a b)
9   (= (remainder b a) 0))
10
11 (define (gcd a b)
12   (if (= b 0)
13     a
14     (gcd b (remainder a b))))
15
16 ;; naive fibonacci definition
17 (define (fib n)
18   (cond 
19     ((or (= n 0) (= n 1)) 1)
20     (else (+ (fib (- n 1))
21              (fib (- n 2))))))
22
23 (define (range low high (step 1))
24   (cond 
25     ((or (and (< low high)
26               (positive? step))
27          (and (> low high)
28           (negative? step)))
29      (cons low (range (+ low step) high step)))
30     (else '())))
31
32 (define (accumulate op initial coll)
33   (if (empty? coll)
34       initial
35       (op (car coll)
36           (accumulate op initial (cdr coll)))))
37
38 (provide square fib range accumulate)