-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmagic-write.rkt
71 lines (58 loc) · 2.58 KB
/
magic-write.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
#lang racket
(require rackunit)
(provide write-to-string
read-from-string
string->struct/maker
vectors->structs)
;; writes a value into a string
(define (write-to-string val)
(with-output-to-string
(lambda () (write val))))
;; reads a value from a string
(define (read-from-string str)
(with-input-from-string str read))
;; turn strings into structures recursively
;; (listof (list/c symbol maker)) string -> any
(define (string->struct/maker maker-table string)
(define vectorized (read-from-string string))
(vectors->structs maker-table vectorized))
;; find all vectors, turn them into the corresponding structures
(define (vectors->structs table data)
(cond
[(vector? data)
(unless (<= 1 (vector-length data))
(raise-argument-error 'vector->structs "vector of length 1 or more"
1 table data))
(define label (vector-ref data 0))
(match (regexp-match #px"^struct:(.*)$" (symbol->string label))
[(list _ name)
(match (assoc name table)
[#f (raise-argument-error 'vectors->structs
"struct with name appearing in table"
1 table data)]
[(list dc maker) (apply maker (map (lambda (data)
(vectors->structs table data))
(rest (vector->list data))))])])]
[(list? data)
(map (lambda (data) (vectors->structs table data)) data)]
[else data]))
(check-equal? (write-to-string (list 3 4 5))
"(3 4 5)")
(check-equal? (read-from-string "(3 4 5)")
(list 3 4 5))
(define-struct jar (la di) #:transparent)
(define my-table (list (list "jar" make-jar)))
(check-equal? (string->struct/maker my-table
(write-to-string (make-jar "abc" 34)))
(make-jar "abc" 34))
(check-equal? (string->struct/maker my-table
(write-to-string (make-jar "abc"
(make-jar
3 3))))
(make-jar "abc" (make-jar 3 3)))
(check-equal? (string->struct/maker my-table
(write-to-string (make-jar "abc"
(list
(make-jar
3 3)))))
(make-jar "abc" (list (make-jar 3 3))))