Makes SPARQL AVG aggregate function simpler

pull/537/head
Tpt 1 year ago committed by Thomas Tanon
parent 1f89bef860
commit 8c68cf4041
  1. 22
      lib/src/sparql/eval.rs

@ -4533,30 +4533,30 @@ impl Accumulator for SumAccumulator {
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct AvgAccumulator { struct AvgAccumulator {
sum: SumAccumulator, sum: SumAccumulator,
count: CountAccumulator, count: i64,
} }
impl Accumulator for AvgAccumulator { impl Accumulator for AvgAccumulator {
fn add(&mut self, element: Option<EncodedTerm>) { fn add(&mut self, element: Option<EncodedTerm>) {
self.sum.add(element.clone()); self.sum.add(element);
self.count.add(element); self.count += 1;
} }
fn state(&self) -> Option<EncodedTerm> { fn state(&self) -> Option<EncodedTerm> {
let sum = self.sum.state()?; let sum = self.sum.state()?;
let count = self.count.state()?; if self.count == 0 {
if count == EncodedTerm::from(0) {
Some(0.into()) Some(0.into())
} else { } else {
//TODO: deduplicate? //TODO: deduplicate?
//TODO: duration? //TODO: duration?
match NumericBinaryOperands::new(sum, count)? { let count = Integer::from(self.count);
NumericBinaryOperands::Float(v1, v2) => Some((v1 / v2).into()), match sum {
NumericBinaryOperands::Double(v1, v2) => Some((v1 / v2).into()), EncodedTerm::FloatLiteral(sum) => Some((sum / Float::from(count)).into()),
NumericBinaryOperands::Integer(v1, v2) => { EncodedTerm::DoubleLiteral(sum) => Some((sum / Double::from(count)).into()),
Decimal::from(v1).checked_div(v2).map(Into::into) EncodedTerm::IntegerLiteral(sum) => {
Some(Decimal::from(sum).checked_div(count)?.into())
} }
NumericBinaryOperands::Decimal(v1, v2) => v1.checked_div(v2).map(Into::into), EncodedTerm::DecimalLiteral(sum) => Some(sum.checked_div(count)?.into()),
_ => None, _ => None,
} }
} }

Loading…
Cancel
Save