use std::cmp::Ordering;
use crate::expr::stats::Precision;
use crate::expr::stats::Stat;
use crate::expr::stats::bound::IntersectionResult;
use crate::partial_ord::partial_min;
pub trait StatType<T> {
type Bound: StatBound<T>;
const STAT: Stat;
}
pub trait StatBound<T>: Sized {
fn lift(value: Precision<T>) -> Self;
fn into_value(self) -> Precision<T>;
fn union(&self, other: &Self) -> Option<Self>;
fn intersection(&self, other: &Self) -> Option<IntersectionResult<Self>>;
fn to_exact(&self) -> Option<&T>;
}
impl<T> Precision<T> {
pub fn bound<S: StatType<T>>(self) -> S::Bound {
S::Bound::lift(self)
}
}
impl<T: PartialOrd + Clone> StatBound<T> for Precision<T> {
fn lift(value: Precision<T>) -> Self {
value
}
fn into_value(self) -> Precision<T> {
self
}
fn union(&self, other: &Self) -> Option<Self> {
self.clone()
.zip(other.clone())
.map(|(lhs, rhs)| partial_min(&lhs, &rhs).cloned())
.transpose()
}
fn intersection(&self, other: &Self) -> Option<IntersectionResult<Self>> {
Some(match (self, other) {
(Precision::Exact(lhs), Precision::Exact(rhs)) => {
if lhs.partial_cmp(rhs)? == Ordering::Equal {
IntersectionResult::Value(Precision::Exact(lhs.clone()))
} else {
IntersectionResult::None
}
}
(Precision::Exact(exact), Precision::Inexact(inexact))
| (Precision::Inexact(inexact), Precision::Exact(exact)) => {
if exact.partial_cmp(inexact)? == Ordering::Less {
IntersectionResult::Value(Precision::Inexact(exact.clone()))
} else {
IntersectionResult::Value(Precision::Exact(exact.clone()))
}
}
(Precision::Inexact(lhs), Precision::Inexact(rhs)) => {
IntersectionResult::Value(Precision::Inexact(partial_min(lhs, rhs)?.clone()))
}
})
}
fn to_exact(&self) -> Option<&T> {
match self {
Precision::Exact(val) => Some(val),
_ => None,
}
}
}