# A String -> U32 map built in parallel: entries go to one of 2^depth buckets by their key's FNV-1a hash, a bit a # level, the two halves of each level built at the same time, and each bucket is a Base Map. 0 means absent, as # Map.get with default 0 answers. import Base type HM is Data: HLeaf{m: Map<&2, U32>} HNode{l: HM, r: HM} type HE is Data: HE{h: U32, k: String, v: U32} def hash_go(s: String, +h: U32) -> U32: match s: case SNil{}: h case SCon{c, t}: hash_go(t, (U32.xor(h, Char.to_u32(c)) * 16777619 : U32)) def hash(s: String) -> U32: hash_go(s, 2166136261) def entry(+k: String, v: U32) -> HE: HE{hash(k), k, v} def fill(es: List<&2, HE>, m: Map<&2, U32>) -> Map<&2, U32>: match es: case []: m case HE{h, k, v} <> t: fill(t, Map.set(&2, U32, m, k, v)) def he_bit(e: HE, +bit: U32) -> Bool: match e: case HE{h, k, v}: U32.is_ne(U32.and(h, bit), 0) def keep_if(ok: Bool, e: HE, rest: List<&2, HE>) -> List<&2, HE>: match ok: case True{}: e <> rest case False{}: rest # the entries whose hash bit is `side` def keep(es: List<&2, HE>, +bit: U32, +side: Bool) -> List<&2, HE>: match es: case []: [] case +e <> t: keep_if(Bool.not(Bool.xor(he_bit(e, bit), side)), e, keep(t, bit, side)) # entries in a tree of lists, as a parallel build of them gives them type ETr is Data: TLeaf{es: List<&2, HE>} TNode{l: ETr, r: ETr} def flat_go(t: ETr, acc: List<&2, HE>) -> List<&2, HE>: match t: case TLeaf{es}: List.append(&2, HE, es, acc) case TNode{l, r}: flat_go(l, flat_go(r, acc)) def flat(t: ETr) -> List<&2, HE>: flat_go(t, []) def build_go(depth: Nat, +bit: U32, +es: List<&2, HE>) -> HM: match depth: case 0n: HLeaf{fill(es, Map.new(&2, U32))} case 1n+ +d: l r = build_go(d, (bit * 2 : U32), keep(es, bit, False{})) build_go(d, (bit * 2 : U32), keep(es, bit, True{})) HNode{l, r} # a map of the entries, in 64 buckets def build(+es: List<&2, HE>) -> HM: build_go(6n, 1, es) def side(right: Bool, go_l: Unit -> U32, go_r: Unit -> U32) -> U32: match right: case True{}: go_r(Unit{}) case False{}: go_l(Unit{}) def get_leaf(r: Map<&2, U32> & U32) -> U32: match r: case (m, v): v def get_go(m: HM, +h: U32, +bit: U32, +k: String) -> U32: match m: case HLeaf{mm}: get_leaf(Map.get(U32, 0, mm, k)) case HNode{l, r}: side(U32.is_ne(U32.and(h, bit), 0), u => get_go(l, h, (bit * 2 : U32), k), u => get_go(r, h, (bit * 2 : U32), k)) # the value of k, or 0 def get(m: HM, +k: String) -> U32: get_go(m, hash(k), 1, k) # every entry, as (key, value) pairs def pairs_go(m: HM, acc: List<&2, Sigma<&2, &2, String, _ => U32>>) -> List<&2, Sigma<&2, &2, String, _ => U32>>: match m: case HLeaf{mm}: List.append(&2, Sigma<&2, &2, String, _ => U32>, Map.to_list(&2, U32, mm), acc) case HNode{l, r}: pairs_go(l, pairs_go(r, acc)) def pairs(m: HM) -> List<&2, Sigma<&2, &2, String, _ => U32>>: pairs_go(m, [])