mirror of
https://github.com/xai-org/x-algorithm.git
synced 2026-02-13 03:05:06 +01:00
46 lines
1.3 KiB
Rust
46 lines
1.3 KiB
Rust
use crate::util;
|
|
use std::any::type_name_of_val;
|
|
|
|
pub trait Selector<Q, C>: Send + Sync
|
|
where
|
|
Q: Clone + Send + Sync + 'static,
|
|
C: Clone + Send + Sync + 'static,
|
|
{
|
|
/// Default selection: sort and truncate based on provided configs
|
|
fn select(&self, _query: &Q, candidates: Vec<C>) -> Vec<C> {
|
|
let mut sorted = self.sort(candidates);
|
|
if let Some(limit) = self.size() {
|
|
sorted.truncate(limit);
|
|
}
|
|
sorted
|
|
}
|
|
|
|
/// Decide if this selector should run for the given query
|
|
fn enable(&self, _query: &Q) -> bool {
|
|
true
|
|
}
|
|
|
|
/// Extract the score from a candidate to use for sorting.
|
|
fn score(&self, candidate: &C) -> f64;
|
|
|
|
/// Sort candidates by their scores in descending order.
|
|
fn sort(&self, candidates: Vec<C>) -> Vec<C> {
|
|
let mut sorted = candidates;
|
|
sorted.sort_by(|a, b| {
|
|
self.score(b)
|
|
.partial_cmp(&self.score(a))
|
|
.unwrap_or(std::cmp::Ordering::Equal)
|
|
});
|
|
sorted
|
|
}
|
|
|
|
/// Optionally provide a size to select. Defaults to no truncation if not overridden.
|
|
fn size(&self) -> Option<usize> {
|
|
None
|
|
}
|
|
|
|
fn name(&self) -> &'static str {
|
|
util::short_type_name(type_name_of_val(self))
|
|
}
|
|
}
|