-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap_basics.mere
More file actions
70 lines (65 loc) · 2.43 KB
/
Copy pathmap_basics.mere
File metadata and controls
70 lines (65 loc) · 2.43 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
// Phase 12.10: Map[R, K, V] — region-aware mutable associative map.
//
// Design context: internal design notes §5
//
// `Map[R, K, V]` is a region-scoped mutable associative array. It follows
// the same construction-time binding pattern as Vec[R, T] / StrBuf[R].
// Internally it uses OCaml Hashtbl (polymorphic hash/eq), with the
// expectation that Lang's primitive values (int / str / bool / tuple of
// primitives) are used as keys.
//
// API:
// map_new : unit -> Map[R, K, V] (binds to region, or __heap if outside)
// map_set : Map[R, K, V] -> K -> V -> unit
// map_get : Map[R, K, V] -> K -> V (eval error if key is absent)
// map_has : Map[R, K, V] -> K -> bool
// map_len : Map[R, K, V] -> int
// len (polymorphic) : Map[R, K, V] -> int also works the same way
{
// === Pattern 1: simple str -> int map ===
let counts = map_new () in
let _ = map_set counts "apple" 3 in
let _ = map_set counts "banana" 5 in
let _ = map_set counts "cherry" 2 in
let _ = print ("apple count = " ++ show (map_get counts "apple")) in
let _ = print ("total = " ++ show (
map_get counts "apple" + map_get counts "banana" + map_get counts "cherry")
) in
let _ = print ("map_len = " ++ show (map_len counts)) in
// === Pattern 2: safely get after checking existence with map_has ===
let lookup =
if map_has counts "apple" then map_get counts "apple"
else 0 in
let missing_ok =
if map_has counts "absent" then map_get counts "absent"
else (-1) in
let _ = print ("present = " ++ show lookup) in
let _ = print ("missing = " ++ show missing_ok) in
// === Pattern 3: int -> str (works naturally with reversed types) ===
let codes = map_new () in
let _ = map_set codes 1 "ok" in
let _ = map_set codes 404 "not found" in
let _ = map_set codes 500 "server error" in
let _ = print ("status 404 = " ++ map_get codes 404) in
// === Pattern 4: build a short-lived map inside a region ===
let summary =
region R {
let acc = map_new () in // type: Map[R, str, int]
let _ = map_set acc "a" 1 in
let _ = map_set acc "b" 2 in
let _ = map_set acc "c" 3 in
// the map is bulk-freed at the end of the region (Trivial); only the
// result is converted to str and carried out
"items=" ++ show (len acc)
}
in
print summary
}
// Expected output:
// apple count = 3
// total = 10
// map_len = 3
// present = 3
// missing = -1
// status 404 = not found
// items=3