68 lines
1.7 KiB
Scheme
68 lines
1.7 KiB
Scheme
(define (assert a b)
|
|
(cond ((equal? a b) (display "[ok]"))
|
|
(else
|
|
(display "[error] ")
|
|
(display a)
|
|
(display " != ")
|
|
(display b)))
|
|
(newline))
|
|
|
|
(define (gcd a b)
|
|
(if (= b 0) (abs a) (gcd b (remainder a b))))
|
|
|
|
(define (average a b) (/ (+ a b) 2.0))
|
|
(define (id n) n)
|
|
(define identity id)
|
|
(define (inc n) (+ n 1))
|
|
(define nil '())
|
|
(define (divides? a b) (= (remainder b a) 0))
|
|
(define (cube n) (* n n n))
|
|
(define (even? n) (= (remainder n 2) 0))
|
|
(define (odd? n) (= (remainder n 2) 1))
|
|
|
|
; copied prime? from 1.21
|
|
(define (find-divisor n test-divisor)
|
|
(cond ((> (square test-divisor) n) n)
|
|
((divides? test-divisor n) test-divisor)
|
|
(else (find-divisor n (+ test-divisor 1)))))
|
|
(define (smallest-divisor n)
|
|
(find-divisor n 2))
|
|
(define (prime? n) (if (= n 1) #f (= n (smallest-divisor n))))
|
|
|
|
; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-15.html
|
|
(define (enumerate-interval low high)
|
|
(if (> low high)
|
|
nil
|
|
(cons low (enumerate-interval (+ low 1) high))))
|
|
|
|
; Returns #t if there is no #f in xs, otherwise returns #f.
|
|
(define (all? xs)
|
|
(cond ((null? xs) #t)
|
|
((eq? (car xs) #f) #f)
|
|
(else (all? (cdr xs)))))
|
|
|
|
(define (all-eq? xs)
|
|
(cond ((null? xs) #t)
|
|
((null? (cdr xs)) #t)
|
|
((eq? (car xs) (cadr xs)) (all-eq? (cdr xs)))
|
|
(else #f)))
|
|
|
|
(define (fold-right op initial sequence) ; same as accumulate
|
|
(if (null? sequence)
|
|
initial
|
|
(op (car sequence)
|
|
(fold-right op initial (cdr sequence)))))
|
|
|
|
; From exercise 3.5
|
|
(define (random-in-range low high)
|
|
(let ((range (- high low)))
|
|
(+ low (random range))))
|
|
|
|
(define (contains x xs)
|
|
(cond
|
|
((null? xs) #f)
|
|
((eq? x (car xs)) #t)
|
|
(else (contains x (cdr xs)))))
|
|
|
|
'util-loaded
|