From e74fd11b0dc7c8e099b95552ed9b70ccec3453f3 Mon Sep 17 00:00:00 2001 From: bakaq Date: Sun, 29 Sep 2024 23:06:43 -0300 Subject: [PATCH] Conjunctions, disjunction, and LeafAnswer to PrologTerm --- src/machine/parsed_results.rs | 48 +++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/machine/parsed_results.rs b/src/machine/parsed_results.rs index 6b7e3fc7..93d15ee1 100644 --- a/src/machine/parsed_results.rs +++ b/src/machine/parsed_results.rs @@ -82,6 +82,54 @@ impl PrologTerm { pub fn variable(value: impl Into) -> Self { PrologTerm::Var(value.into()) } + + /// Creates a conjunction, giving the atom `true` if empty. + pub fn conjunction(value: impl IntoIterator) -> Self { + PrologTerm::try_conjunction(value).unwrap_or(PrologTerm::atom("true")) + } + + /// Creates a conjunction, giving `None` if empty. + pub fn try_conjunction(value: impl IntoIterator) -> Option { + let mut iter = value.into_iter(); + iter.next() + .map(|first| { + PrologTerm::try_conjunction(iter) + .map(|rest| PrologTerm::compound(",", [first.clone(), rest])) + .unwrap_or(first) + }) + } + + /// Creates a disjunction, giving the atom `false` if empty. + pub fn disjunction(value: impl IntoIterator) -> Self { + PrologTerm::try_disjunction(value).unwrap_or(PrologTerm::atom("false")) + } + + /// Creates a disjunction, giving `None` if empty. + pub fn try_disjunction(value: impl IntoIterator) -> Option { + let mut iter = value.into_iter(); + iter.next() + .map(|first| { + PrologTerm::try_disjunction(iter) + .map(|rest| PrologTerm::compound(";", [first.clone(), rest])) + .unwrap_or(first) + }) + } +} + +impl From for PrologTerm { + fn from(value: LeafAnswer) -> Self { + match value { + LeafAnswer::True => PrologTerm::atom("true"), + LeafAnswer::False => PrologTerm::atom("false"), + LeafAnswer::Exception(inner) => match inner.clone() { + PrologTerm::Compound(functor, args) if functor == "error" && args.len() == 2 => inner, + _ => PrologTerm::compound("throw", [inner]), + }, + LeafAnswer::LeafAnswer { bindings: _, residual_goals: _ } => { + todo!() + }, + } + } } /// This is an auxiliary function to turn a count into names of anonymous variables like _A, _B, -- 2.54.0