-
Notifications
You must be signed in to change notification settings - Fork 0
/
references.scm
49 lines (38 loc) · 1.03 KB
/
references.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#lang racket
(require (except-in eopl #%module-begin))
(local-require "errors.scm")
(provide reference? newref deref setref!)
;;;;;;;;;;;;;;;; references ;;;;;;;;;;;;;;;;
(define empty-store
(lambda () '()))
(define the-store 'uninitialized)
(define initialize-store!
(lambda ()
(set! the-store (empty-store))))
(initialize-store!)
(define reference?
(lambda (v) (integer? v)))
(define newref
(lambda (val)
(let ((next-ref (length the-store)))
(set! the-store (append the-store (list val)))
next-ref)))
(define deref
(lambda (ref)
(list-ref the-store ref)))
(define setref!
(lambda (ref val)
(set! the-store
(letrec ((setref-inner
(lambda (store1 ref1)
(cond
((null? store1)
(error-invalid-reference))
((zero? ref1)
(cons val (cdr store1)))
(else
(cons
(car store1)
(setref-inner
(cdr store1) (- ref1 1))))))))
(setref-inner the-store ref)))))