import Base # lawful-halves definitions. The laws are in LAWS.bend. # # A task holds a closure Unit -> B that carries its own input; call runs it. # Bend's closures are affine (each is called at most once), so one function # cannot be called at every leaf of a tree: every task carries its own. The # laws compare running tasks in parallel with force, which calls them one # after another, in order. # A task: a closure that holds its own input. (A datatype rather than a bare # closure: proofs then move tasks around as values. A closure passed as an # argument is eta-expanded by bend's elaborator, which the --verdict kernel # does not accept.) type Task is Type: Task{fn: Unit -> B} # What the task gives. def call(b, -B: Kind(b), t: Task) -> B: match t: case Task{k}: k(Unit{}) # Each task called once, in order: the list of their results. def force(b, -B: Kind(b), ts: List<&1, Task>) -> List: match ts: case Nil{}: Nil{} case t <> rest: call(b, B, t) <> force(b, B, rest) # A binary tree of values: none (Tip), one (Leaf), or two subtrees (Node). type Tree is Kind(a): Tip{} Leaf{x: A} Node{l: Tree, r: Tree} # The values of t, left to right. def leaves(a, -A: Kind(a), t: Tree) -> List: match t: case Tip{}: Nil{} case Leaf{x}: x <> Nil{} case Node{l, r}: List.append(a, A, leaves(a, A, l), leaves(a, A, r)) # The shape of t: the same tree with every value replaced by Unit{}. def shape(a, -A: Kind(a), t: Tree) -> Tree<&2, Unit>: match t: case Tip{}: Tip{} case Leaf{x}: Leaf{Unit{}} case Node{l, r}: Node{shape(a, A, l), shape(a, A, r)} # The number of leaves of a shape. def count(+s: Tree<&2, Unit>) -> Nat: match s: case Tip{}: 0n case Leaf{x}: 1n case Node{l, r}: Nat.add(count(l), count(r)) # A balanced shape: at every Node, the left subtree has at least one leaf, and # the right one has as many leaves as the left or one more. So no Tip sits # below a Node, and a tree of n >= 1 leaves is ceil(log2(n)) levels deep. def balanced(+s: Tree<&2, Unit>) -> Bool: match s: case Tip{}: True{} case Leaf{x}: True{} case Node{l, r}: Nat.is_lt(0n, count(l)) && Nat.is_le(count(l), count(r)) && Nat.is_le(count(r), 1n+count(l)) && balanced(l) && balanced(r)