-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinding.rkt
72 lines (63 loc) · 2.43 KB
/
binding.rkt
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#lang racket
;;;; ***************************************************
;;;; Kyle Kaufman, Benjamin Poulin, Kasey Wei
;;;; CSDS 345 Spring 2025
;;;; Group Project 1: Simple Language Interpreter
;;;; ***************************************************
(provide binding-lookup binding-status binding-set binding-create binding-unbound binding-uninit binding-init empty-stt stt-empty?)
; Return bound value of name in state
; Error if binding does not exist
(define (binding-lookup name state)
(cond
[(stt-empty? state) (error (~a name " has not been declared"))]
[(eq? (stt-first-name state) name) (stt-first-val state)]
[else (binding-lookup name (stt-cdr state))]))
; Return binding-unbound if name's binding does not exist in state
; Return binding-uninit if it's not initialized
; Return binding-init otherwise
(define (binding-status name state)
(with-handlers ([exn:fail? (lambda (v) binding-unbound)])
(if (eq? (binding-lookup name state) binding-uninit)
binding-uninit
binding-init)))
(define binding-unbound "unbound")
(define binding-uninit '())
(define binding-init "initialized")
; Return state with value set for name's binding
; Error if binding does not exist
(define (binding-set name value state)
(cond
[(stt-empty? state) (error (~a name " has not been declared"))]
[(eq? (stt-first-name state) name) (stt-cons (list name value) (stt-cdr state))]
[else (stt-cons (stt-car state) (binding-set name value (stt-cdr state)))]))
; Return state with new binding (name, value)
; Error if binding already exists
(define (binding-create name value state)
(cond
[(stt-empty? state) (stt-cons (list name value) empty-stt)]
[(eq? (stt-first-name state) name) (error (~a "Binding for " name " already exists"))]
[else (stt-cons (stt-car state) (binding-create name value (stt-cdr state)))]))
(define empty-stt '(() ()))
(define (stt-empty? state)
(or (null? (stt-names state))
(null? (stt-vals state))))
(define stt-names car)
(define stt-vals cadr)
(define stt-name car)
(define stt-val cadr)
(define (stt-first-name state)
(car (stt-names state)))
(define (stt-first-val state)
(car (stt-vals state)))
(define (stt-car state)
(list
(car (stt-names state))
(car (stt-vals state))))
(define (stt-cdr state)
(list
(cdr (stt-names state))
(cdr (stt-vals state))))
(define (stt-cons pair state)
(list
(cons (stt-name pair) (stt-names state))
(cons (stt-val pair) (stt-vals state))))