tree.bend source
tree.bend on the hub · documented module
# Balanced search trees for the Unicode tables (tables.bend): code point ranges to a value, code points to a list,# and code point pairs to a code point. A lookup walks one path: each node hands the branch it takes to a helper as# a closure, so the branch not taken is never evaluated.import Basetype RT is Data: RTip{} RNode{lo: U32, hi: U32, v: U32, l: RT, r: RT}type KT is Data: KTip{} KNode{k: U32, v: List<&2, U32>, l: KT, r: KT}type PT is Data: PTip{} PNode{a: U32, b: U32, p: U32, l: PT, r: PT}# x below the node, above it, or in itdef rt_side(lt: Bool, gt: Bool, v: U32, go_l: Unit -> U32, go_r: Unit -> U32) -> U32: match lt gt: case True{} _: go_l(Unit{}) case False{} True{}: go_r(Unit{}) case False{} False{}: v# the value of the range holding c, or 0def rt_find(t: RT, +c: U32) -> U32: match t: case RTip{}: 0 case RNode{+lo, +hi, v, l, r}: rt_side(U32.is_lt(c, lo), U32.is_gt(c, hi), v, u => rt_find(l, c), u => rt_find(r, c))def kt_side(lt: Bool, eq: Bool, v: List<&2, U32>, go_l: Unit -> Maybe<&2, List<&2, U32>>, go_r: Unit -> Maybe<&2, List<&2, U32>>) -> Maybe<&2, List<&2, U32>>: match lt eq: case True{} _: go_l(Unit{}) case False{} True{}: Some{v} case False{} False{}: go_r(Unit{})# the list stored for c, if anydef kt_find(t: KT, +c: U32) -> Maybe<&2, List<&2, U32>>: match t: case KTip{}: None{} case KNode{+k, v, l, r}: kt_side(U32.is_lt(c, k), U32.is_eq(c, k), v, u => kt_find(l, c), u => kt_find(r, c))def pt_order2(yb: Bool, ye: Bool) -> U32: match yb ye: case True{} _: 0 case False{} True{}: 1 case False{} False{}: 2# (x, y) against the node's (a, b), in lexicographic orderdef pt_order(xa: Bool, xe: Bool, yb: Bool, ye: Bool) -> U32: match xa xe: case True{} _: 0 case False{} False{}: 2 case False{} True{}: pt_order2(yb, ye)def pt_pick(lt: Bool, eq: Bool, p: U32, go_l: Unit -> Maybe<&2, U32>, go_r: Unit -> Maybe<&2, U32>) -> Maybe<&2, U32>: match lt eq: case True{} _: go_l(Unit{}) case False{} True{}: Some{p} case False{} False{}: go_r(Unit{})def pt_side(+o: U32, p: U32, go_l: Unit -> Maybe<&2, U32>, go_r: Unit -> Maybe<&2, U32>) -> Maybe<&2, U32>: pt_pick(U32.is_eq(o, 0), U32.is_eq(o, 1), p, go_l, go_r)# the code point stored for the pair (x, y), if anydef pt_find(t: PT, +x: U32, +y: U32) -> Maybe<&2, U32>: match t: case PTip{}: None{} case PNode{+a, +b, p, l, r}: pt_side(pt_order(U32.is_lt(x, a), U32.is_eq(x, a), U32.is_lt(y, b), U32.is_eq(y, b)), p, u => pt_find(l, x, y), u => pt_find(r, x, y))