SICP/util.scm

51 lines
1.6 KiB
Scheme
Raw Normal View History

2020-10-20 03:36:17 +02:00
(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))))
2020-10-24 17:24:13 +02:00
(define (average a b) (/ (+ a b) 2.0))
2020-10-26 02:40:51 +01:00
(define (id n) n)
2020-10-31 03:02:12 +01:00
(define identity id)
2020-10-26 02:40:51 +01:00
(define (inc n) (+ n 1))
2020-10-29 16:47:13 +01:00
(define nil '())
2020-10-31 03:02:12 +01:00
(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))
2020-10-24 17:24:13 +02:00
2020-10-31 03:02:12 +01:00
; 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))))
2020-11-17 19:33:55 +01:00
; Put and get functions. We could have implemented this via a list of
; three-tuples, but I don't know how to create global variables yet so we just
; use this code from SO. Doesn't look too complicated.
; https://stackoverflow.com/questions/5499005/how-do-i-get-the-functions-put-and-get-in-sicp-scheme-exercise-2-78-and-on
(define *op-table* (make-hash-table))
(define (put op type proc)
(hash-table/put! *op-table* (list op type) proc))
(define (get op type)
2020-11-18 23:54:54 +01:00
(let ((e (hash-table/get *op-table* (list op type) #f)))
(if (eq? e #f)
(error "Unknown op type -- GET" (list op type))
e)))
2020-11-17 19:33:55 +01:00