-
Notifications
You must be signed in to change notification settings - Fork 1
/
saving.rkt
46 lines (35 loc) · 1.2 KB
/
saving.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
#lang typed/racket
(require "vector.rkt")
(provide Encoded save-to load-from)
(define-type Encoded (U (Listof Encoded) Float String Symbol Boolean Vector2D))
(struct par-vec ([x : Float] [y : Float]) #:prefab)
(define-type Partial (U (Listof Partial) Float String Symbol Boolean par-vec))
(: partial-enc (-> Encoded Partial))
(define (partial-enc x)
(cond ((list? x) (map partial-enc x))
((vec? x) (par-vec (vec-x x) (vec-y x)))
(else x)))
(: partial-dec (-> Any Encoded))
(define (partial-dec x)
(cond ((list? x) (map partial-dec x))
((flonum? x) x)
((string? x) x)
((symbol? x) x)
((boolean? x) x)
((par-vec? x) (vec (par-vec-x x) (par-vec-y x)))
(else (error "invalid encoding"))))
(: save (-> Encoded Output-Port Void))
(define (save x port)
(write (partial-enc x) port))
(: save-to (-> Encoded String Void))
(define (save-to x str)
(call-with-output-file str (curry save x)))
(: load (-> Input-Port Encoded))
(define (load port)
(let ((loaded (partial-dec (read port))))
loaded))
(: load-from (-> String Encoded))
(define (load-from str)
(call-with-input-file str load))
(: encoded? (-> Any Encoded))
(define-predicate encoded? Encoded)