use crate::language::*;
use nar_dev_utils::matches_or;
impl<'a> CompoundTermRef<'a> {
#[doc(alias = "get_relation_index")]
pub fn get_placeholder_index(self) -> usize {
self.components
.iter()
.position(Term::is_placeholder)
.expect("尝试获取「非『像』词项」的关系索引")
}
pub fn get_relation(self) -> &'a Term {
&self.components[0]
}
pub fn get_the_other_component(self) -> Option<&'a Term> {
matches_or! {
?self.components,
[_, term1, term2] => match term1.is_placeholder() {
true => term2,
false => term1,
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::symbols::*;
use crate::test_compound as compound;
use crate::test_term as term;
use crate::{ok, util::AResult};
use nar_dev_utils::asserts;
#[test]
fn instanceof_image() -> AResult {
fn make_image(
argument: impl IntoIterator<Item = &'static str>,
make_vec: impl Fn(Vec<Term>) -> Option<Term>,
) -> AResult<Term> {
let argument = argument
.into_iter()
.map(|t| t.parse::<Term>().expect("内部词项解析失败"))
.collect::<Vec<_>>();
make_vec(argument).ok_or(anyhow::anyhow!("词项解析失败"))
}
fn make_ext(argument: impl IntoIterator<Item = &'static str>) -> AResult<Term> {
make_image(argument, Term::make_image_ext_vec)
}
fn make_int(argument: impl IntoIterator<Item = &'static str>) -> AResult<Term> {
make_image(argument, Term::make_image_int_vec)
}
asserts! {
term!(r"(/, _, A, B)").identifier() => PRODUCT_OPERATOR,
term!(r"(\, _, A, B)").identifier() => PRODUCT_OPERATOR,
make_ext(["S", "_", "A", "B"])?.instanceof_image()
make_int(["S", "_", "A", "B"])?.instanceof_image()
make_ext(["S", "A", "_", "B"])?.instanceof_image()
make_int(["S", "A", "_", "B"])?.instanceof_image()
make_ext(["S", "A", "B", "_"])?.instanceof_image()
make_int(["S", "A", "B", "_"])?.instanceof_image()
term!(r"(/, A, _, B)").instanceof_image()
term!(r"(\, A, _, B)").instanceof_image()
term!(r"(/, A, B, _)").instanceof_image()
term!(r"(\, A, B, _)").instanceof_image()
}
ok!()
}
#[test]
fn get_relation_index() -> AResult {
asserts! {
compound!(r"(/, A, _, B)").get_placeholder_index() => 1
compound!(r"(\, A, _, B)").get_placeholder_index() => 1
compound!(r"(/, A, B, _)").get_placeholder_index() => 2
compound!(r"(\, A, B, _)").get_placeholder_index() => 2
}
ok!()
}
#[test]
fn get_relation() -> AResult {
asserts! {
compound!(r"(/, R, _, B)").get_relation() => &term!("R")
compound!(r"(\, R, _, B)").get_relation() => &term!("R")
compound!(r"(/, R, A, _)").get_relation() => &term!("R")
compound!(r"(\, R, A, _)").get_relation() => &term!("R")
}
ok!()
}
#[test]
fn get_the_other_component() -> AResult {
asserts! {
compound!(r"(/, R, _, B)").get_the_other_component() => Some(&term!("B"))
compound!(r"(\, R, _, B)").get_the_other_component() => Some(&term!("B"))
compound!(r"(/, R, A, _)").get_the_other_component() => Some(&term!("A"))
compound!(r"(\, R, A, _)").get_the_other_component() => Some(&term!("A"))
}
ok!()
}
}