Repository navigation
Expand file tree
/
Copy pathrecord.rv
More file actions
76 lines (63 loc) · 1.6 KB
/
Copy pathrecord.rv
File metadata and controls
76 lines (63 loc) · 1.6 KB
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
# Struct-like record backed by ordered tag/value pairs.
import { ... } from "./core.rv"
import { ... } from "./bootstrap.rv"
export { Pair, Record, record, keyindex, setkey, upsertkey, getkey, haskey, merge }
bundle Pair(k: Tag, v)
bundle Record(fields...)
@extend
fn show(p: Pair) {
show(part(p, 1))
print(" => ")
show(part(p, 2))
}
fn record(fields...) { Record(fields...) }
@extend
fn length(r: Record) { nparts(r) }
fn keyindex(r: Record, k: Tag) {
i = 1
while i < length(r) + 1 {
if part(part(r, i), 1) == k { return i }
i = i + 1
}
return nil
}
fn haskey(r: Record, k: Tag) { !nil?(keyindex(r, k)) }
fn getkey(r: Record, k: Tag) {
i = keyindex(r, k)
if nil?(i) { abort(concat("No such key: ", string(k))) }
return part(part(r, notnil(i)), 2)
}
fn setkey(&r: Record, k: Tag, v) {
i = keyindex(r, k)
if nil?(i) { abort(concat("No such key: ", string(k))) }
r = tag"common.core/set"(r, notnil(i), Pair(k, v))
}
fn upsertkey(&r: Record, k: Tag, v) {
i = keyindex(r, k)
if nil?(i) {
r = packcat(r, pack(Record, Pair(k, v)))
} else {
r = tag"common.core/set"(r, notnil(i), Pair(k, v))
}
}
fn merge(&r: Record, k: Tag, v) {
i = keyindex(r, k)
if nil?(i) {
r = packcat(r, pack(Record, Pair(k, v)))
return r
}
if part(part(r, notnil(i)), 2) == v { return r }
return r = nil
}
# Returns nil on key clashes; intended for pattern matching.
fn merge(&r: Record, other: Record) {
i = 1
while i < length(other) + 1 {
p = part(other, i)
merge(&r, part(p, 1), part(p, 2))
if nil?(r) { return r = nil }
r = notnil(r)
i = i + 1
}
return r
}