BinaryTreesTreeOf for BalancedTrees

This commit is contained in:
AF 2023-06-16 13:51:00 +00:00
parent 0b29004de2
commit 93c591d576

View File

@ -1,13 +1,7 @@
use super::*; use super::*;
pub trait BinaryTreesUnbalanced<'a>: BinaryTreesHeight<'a> { pub trait BinaryTreesUnbalanced<'a>: BinaryTreesHeight<'a> {
fn tree_with_height( fn tree_of_with_height(&self, node: Self::Node, height: u64) -> BTWrap<'a, Self, Self::Tree>;
&self,
tl: Self::Tree,
key: Self::Key,
tr: Self::Tree,
height: u64,
) -> BTWrap<'a, Self, Self::Tree>;
fn balancing_error<T: 'a>(&self, error: BalancingError) -> BTWrap<'a, Self, T>; fn balancing_error<T: 'a>(&self, error: BalancingError) -> BTWrap<'a, Self, T>;
@ -21,6 +15,11 @@ pub trait BinaryTreesUnbalanced<'a>: BinaryTreesHeight<'a> {
Err(e) => self.balancing_error(e), Err(e) => self.balancing_error(e),
} }
} }
fn node_heights(&self, node: &Self::Node) -> (u64, u64) {
let (tl, tr, _) = self.split(node);
(self.height(&tl), self.height(&tr))
}
} }
#[derive(Clone)] #[derive(Clone)]
@ -89,8 +88,7 @@ impl<'a, BT: BinaryTreesUnbalanced<'a>> BinaryTrees<'a> for BalancedTrees<BT> {
let hp = *hp; let hp = *hp;
let ctx = self.0.clone(); let ctx = self.0.clone();
Self::bind(self.0.resolve(reference), move |node| { Self::bind(self.0.resolve(reference), move |node| {
let (tl, tr, _) = ctx.split(&node); let (hl, hr) = ctx.node_heights(&node);
let (hl, hr) = (ctx.height(&tl), ctx.height(&tr));
ctx.balancing_bind(matches_height(hl, hr, hp), |_| Self::pure(node)) ctx.balancing_bind(matches_height(hl, hr, hp), |_| Self::pure(node))
}) })
} }
@ -103,3 +101,12 @@ impl<'a, BT: BinaryTreesUnbalanced<'a>> BinaryTrees<'a> for BalancedTrees<BT> {
Some((self.0.refer(tree)?, self.0.height(tree))) Some((self.0.refer(tree)?, self.0.height(tree)))
} }
} }
impl<'a, BT: BinaryTreesUnbalanced<'a>> BinaryTreesTreeOf<'a> for BalancedTrees<BT> {
fn tree_of(&self, node: Self::Node) -> BTWrap<'a, Self, Self::Tree> {
let (hl, hr) = self.0.node_heights(&node);
self.0.balancing_bind(parent_height(hl, hr), |height| {
self.0.tree_of_with_height(node, height)
})
}
}