1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;; Standard Library Procedures and Macros ;;
3 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
10 (define (caar l) (car (car l)))
11 (define (cadr l) (car (cdr l)))
12 (define (cdar l) (cdr (car l)))
13 (define (cddr l) (cdr (cdr l)))
14 (define (cadar l) (car (cdr (car l))))
16 ; Return number of items in list
18 (define (iter a count)
21 (iter (cdr a) (+ count 1))))
24 ; Join two lists together
28 (cons (car l1) (join (cdr l1) l2))))
30 ; Append an arbitrary number of lists together
31 (define (append . lists)
34 (if (null? (cdr lists))
36 (join (car lists) (apply append (cdr lists))))))
38 ; Reverse the contents of a list
42 (append (reverse (cdr l)) (list (car l)))))
45 ;; LIBRARY SPECIAL FORMS
49 (define (let-vars args)
52 (cons (caar args) (let-vars (cdr args)))))
54 (define (let-inits args)
57 (cons (cadar args) (let-inits (cdr args)))))
59 (define-macro (let args . body)
60 `((lambda ,(let-vars args)
61 ,@body) ,@(let-inits args)))
65 (define-macro (while condition . body)
66 (let ((loop (gensym)))
70 (begin ,@body (,loop))))
75 (define (cond-predicate clause) (car clause))
76 (define (cond-actions clause) (cdr clause))
77 (define (cond-else-clause? clause)
78 (eq? (cond-predicate clause) 'else))
80 (define (expand-clauses clauses)
83 (let ((first (car clauses))
85 (if (cond-else-clause? first)
87 `(begin ,@(cond-actions first))
88 (error "else clause isn't last in cond expression."))
89 `(if ,(cond-predicate first)
90 (begin ,@(cond-actions first))
91 ,(expand-clauses rest))))))
93 (define-macro (cond . clauses)
95 (error "cond requires at least one clause.")
96 (expand-clauses clauses)))
100 (define (expand-and-expressions expressions)
101 (let ((first (car expressions))
102 (rest (cdr expressions)))
106 ,(expand-and-expressions rest)
109 (define-macro (and . expressions)
110 (if (null? expressions)
112 (expand-and-expressions expressions)))
116 (define (expand-or-expressions expressions)
117 (if (null? expressions)
119 (let ((first (car expressions))
120 (rest (cdr expressions))
122 `(let ((,val ,first))
125 ,(expand-or-expressions rest))))))
127 (define-macro (or . expressions)
128 (expand-or-expressions expressions))
133 (define-macro (backwards . body)
134 (cons 'begin (reverse body)))
136 ; Test for the while macro.
140 (display counter) (newline)
141 (set! counter (- counter 1))))
143 ; Basic iterative summation. Run this on large numbers to
144 ; test garbage collection and tail-call optimization.
147 (define (sum-iter total count maxcount)
148 (if (> count maxcount)
150 (sum-iter (+ total count) (+ count 1) maxcount)))
154 ; Recursive summation. Use this to compare with tail call
155 ; optimized iterative algorithm.
156 (define (sum-recurse n)
159 (+ n (sum-recurse (- n 1)))))