-
Notifications
You must be signed in to change notification settings - Fork 0
/
std.xin
134 lines (119 loc) · 2.57 KB
/
std.xin
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
; standard library
; boolean aliases
(: true 1)
(: false 0)
; want to be able to say "pass"
; on useless if-else cases, for example
(: pass 0)
(: and &)
(: or |)
(: not !)
(: (bool x)
(if x 'true' 'false'))
; type assertions
(: (int? x)
(= (type x) int))
(: (frac? x)
(= (type x) frac))
(: (str? x)
(= (type x) str))
(: (vec? x)
(= (type x) vec))
(: (map? x)
(= (type x) map))
(: (stream? x)
(= (type x) stream))
(: form (type type))
(: (form? x)
(= (type x) form))
; identity function
(: (identity x) x)
; formatted logging shorthand
(: log os::log)
(: (logf s items)
(log (str::fmt s items)))
; basic math
(: (!= a b) (! (= a b)))
(: (>= a b) (! (< a b)))
(: (<= a b) (! (> a b)))
(: (sqrt x) (^ x .5))
(: (neg n) (- 0 n))
(: (pos? n) (> n 0))
(: (neg? n) (< n 0))
(: (zero? x) (= x 0))
(: (inc n) (+ n 1))
(: (dec n) (- n 1))
(: (factor? big small)
(= (% big small) 0))
(: (even? n) (factor? n 2))
(: (odd? n) (! (even? n)))
(: (max a b)
(if (> a b) a b))
(: (min a b)
(if (< a b) a b))
; iteration primitives
(: (range start end step)
((: (sub i acc)
(if (< i end)
(sub (+ i step)
(vec::add! acc i))
acc))
start (vec)))
(: (seq n)
(range 0 n 1))
(: (nat n)
(range 1 (inc n) 1))
(: (take v n)
(vec::slice v 0 n))
(: (loop n f)
((: (sub i)
(if (< i n)
(do (f i)
(sub (+ i 1)))
0))
0))
; set abstraction over map
(: (set)
(map))
(: (set::add! s v)
(map::set! s v 0))
(: set::del! map::del!)
(: set::has? map::has?)
(: set::size map::size)
(: set::items map::keys)
; hex encoding/decoding
(: to-hex-digits
(vec '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' 'a' 'b' 'c' 'd' 'e' 'f'))
(: (hex::enc n)
(if (< n 16)
(vec::get to-hex-digits (int n))
(+ (hex::enc (/ n 16))
(vec::get to-hex-digits (int (% n 16))))))
(: to-dec-number-map
(do (: m (map))
(map::set! m 'a' 10)
(map::set! m 'b' 11)
(map::set! m 'c' 12)
(map::set! m 'd' 13)
(map::set! m 'e' 14)
(map::set! m 'f' 15)))
(: (to-dec-number s)
(if (str::digit? s)
(int s)
(map::get to-dec-number-map s)))
(: (hex::dec s)
(if (= (str::size s) 1)
(to-dec-number s)
(+ (* (hex::dec (str::slice s 0 (dec (str::size s))))
16)
(to-dec-number (str::get s (dec (str::size s)))))))
; drain a source stream
(: (->> file cb)
(if (zero? file)
0
((: (sub acc)
(-> file (: (f buf)
(if (zero? buf)
(cb acc)
(sub (str::add! acc buf))))))
'')))