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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
` the ink standard library `

log := val => out(string(val) + '
')

scan := cb => (
	acc := ['']
	in(evt => evt.type :: {
		'end' -> cb(acc.0)
		'data' -> (
			acc.0 := acc.0 + slice(evt.data, 0, len(evt.data) - 1)
			false
		)
	})
)

` hexadecimal conversion utility functions `
hToN := {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15}
nToH := '0123456789abcdef'

` take number, return hex string `
hex := n => (sub := (p, acc) => p < 16 :: {
	true -> nToH.(p) + acc
	false -> sub(floor(p / 16), nToH.(p % 16) + acc)
})(floor(n), '')

` take hex string, return number `
xeh := s => (
	` i is the num of places from the left, 0-indexed `
	max := len(s)
	(sub := (i, acc) => i :: {
		max -> acc
		_ -> sub(i + 1, acc * 16 + hToN.(s.(i)))
	})(0, 0)
)

` find minimum in list `
min := numbers => reduce(numbers, (acc, n) => n < acc :: {
	true -> n
	false -> acc
}, numbers.0)

` find maximum in list `
max := numbers => reduce(numbers, (acc, n) => n > acc :: {
	true -> n
	false -> acc
}, numbers.0)

` like Python's range(), but no optional arguments `
range := (start, end, step) => (
	span := end - start
	sub := (i, v, acc) => (v - start) / span < 1 :: {
		true -> (
			acc.(i) := v
			sub(i + 1, v + step, acc)
		)
		false -> acc
	}

	` preempt potential infinite loops `
	(end - start) / step > 0 :: {
		true -> sub(0, start, [])
		false -> []
	}
)

` clamp start and end numbers to ranges, such that
	start < end. Utility used in slice `
clamp := (start, end, min, max) => (
	start := (start < min :: {
		true -> min
		false -> start
	})
	end := (end < min :: {
		true -> min
		false -> end
	})
	end := (end > max :: {
		true -> max
		false -> end
	})
	start := (start > end :: {
		true -> end
		false -> start
	})

	{
		start: start
		end: end
	}
)

` get a substring of a given string, or sublist of a given list `
slice := (s, start, end) => (
	` bounds checks `
	x := clamp(start, end, 0, len(s))
	start := x.start
	max := x.end - start

	(sub := (i, acc) => i :: {
		max -> acc
		_ -> sub(i + 1, acc.(i) := s.(start + i))
	})(0, type(s) :: {
		'string' -> ''
		'composite' -> []
	})
)

` join one list to the end of another, return the original first list `
append := (base, child) => (
	baseLength := len(base)
	childLength := len(child)
	(sub := i => i :: {
		childLength -> base
		_ -> (
			base.(baseLength + i) := child.(i)
			sub(i + 1)
		)
	})(0)
)

` join one list to the end of another, return the third list `
join := (base, child) => append(clone(base), child)

` clone a composite value `
clone := x => type(x) :: {
	'string' -> '' + x
	'composite' -> reduce(keys(x), (acc, k) => acc.(k) := x.(k), {})
	_ -> x
}

` tail recursive numeric list -> string converter `
stringList := list => '[' + cat(map(list, string), ', ') + ']'

` tail recursive reversing a list `
reverse := list => (sub := (acc, i) => i < 0 :: {
	true -> acc
	_ -> sub(acc.len(acc) := list.(i), i - 1)
})([], len(list) - 1)

` tail recursive map `
map := (list, f) => reduce(list, (l, item, i) => l.(i) := f(item, i), {})

` tail recursive filter `
filter := (list, f) => reduce(list, (l, item, i) => f(item, i) :: {
	true -> l.len(l) := item
	_ -> l
}, [])

` tail recursive reduce `
reduce := (list, f, acc) => (
	max := len(list)
	(sub := (i, acc) => i :: {
		max -> acc
		_ -> sub(i + 1, f(acc, list.(i), i))
	})(0, acc)
)

` tail recursive reduce from list end `
reduceBack := (list, f, acc) => (sub := (i, acc) => i :: {
	~1 -> acc
	_ -> sub(i - 1, f(acc, list.(i), i))
})(len(list) - 1, acc)

` flatten by depth 1 `
flatten := list => reduce(list, append, [])

` true iff some items in list are true `
some := list => reduce(list, (acc, x) => acc | x, false)

` true iff every item in list is true `
every := list => reduce(list, (acc, x) => acc & x, true)

` concatenate (join) a list of strings into a string `
cat := (list, joiner) => max := len(list) :: {
	0 -> ''
	_ -> (sub := (i, acc) => i :: {
		max -> acc
		_ -> sub(i + 1, acc.len(acc) := joiner + list.(i))
	})(1, clone(list.0))
}

` for-each loop over a list `
each := (list, f) => (
	max := len(list)
	(sub := i => i :: {
		max -> ()
		_ -> (
			f(list.(i), i)
			sub(i + 1)
		)
	})(0)
)

` encode string buffer into a number list `
encode := str => (
	max := len(str)
	(sub := (i, acc) => i :: {
		max -> acc
		_ -> sub(i + 1, acc.(i) := point(str.(i)))
	})(0, [])
)

` decode number list into an ascii string `
decode := data => reduce(data, (acc, cp) => acc.len(acc) := char(cp), '')

` utility for reading an entire file `
readFile := (path, cb) => (
	BufSize := 4096 ` bytes `
	(sub := (offset, acc) => read(path, offset, BufSize, evt => evt.type :: {
		'error' -> cb(())
		'data' -> (
			dataLen := len(evt.data)
			dataLen = BufSize :: {
				true -> sub(offset + dataLen, acc.len(acc) := evt.data)
				false -> cb(acc.len(acc) := evt.data)
			}
		)
	}))(0, '')
)

` utility for writing an entire file
	it's not buffered, because it's simpler, but may cause jank later
	we'll address that if/when it becomes a performance issue `
writeFile := (path, data, cb) => delete(path, evt => evt.type :: {
	` write() by itself will not truncate files that are too long,
		so we delete the file and re-write. Not efficient, but writeFile
		is not meant for large files `
	'end' -> write(path, 0, data, evt => evt.type :: {
		'error' -> cb(())
		'end' -> cb(true)
	})
	_ -> cb(())
})

` template formatting with {{ key }} constructs `
format := (raw, values) => (
	` parser state `
	state := {
		` current position in raw `
		idx: 0
		` parser internal state:
			0 -> normal
			1 -> seen one {
			2 -> seen two {
			3 -> seen a valid } `
		which: 0
		` buffer for currently reading key `
		key: ''
		` result build-up buffer `
		buf: ''
	}

	` helper function for appending to state.buf `
	append := c => state.buf := state.buf + c

	` read next token, update state `
	readNext := () => (
		c := raw.(state.idx)

		state.which :: {
			0 -> c :: {
				'{' -> state.which := 1
				_ -> append(c)
			}
			1 -> c :: {
				'{' -> state.which := 2
				` if it turns out that earlier brace was not
					a part of a format expansion, just backtrack `
				_ -> (
					append('{' + c)
					state.which := 0
				)
			}
			2 -> c :: {
				'}' -> (
					` insert key value `
					state.buf := state.buf + string(values.(state.key))
					state.key := ''
					state.which := 3
				)
				` ignore spaces in keys -- not allowed `
				' ' -> ()
				_ -> state.key := state.key + c
			}
			3 -> c :: {
				'}' -> state.which := 0
				` ignore invalid inputs -- treat them as nonexistent `
				_ -> ()
			}
		}

		state.idx := state.idx + 1
	)

	` main recursive sub-loop `
	max := len(raw)
	(sub := () => state.idx < max :: {
		true -> (
			readNext()
			sub()
		)
		false -> state.buf
	})()
)