//backward chain public Clause Infer(string goal_variable, List <Clause> unproved_conditions) { Clause conclusion = null; List <Rule> goal_stack = new List <Rule>(); foreach (Rule rule in m_rules) { Clause consequent = rule.getConsequent(); if (consequent.Variable == goal_variable) { goal_stack.Add(rule); } } foreach (Rule rule in goal_stack) { rule.FirstAntecedent(); bool goal_reached = true; while (rule.HasNextAntecedents()) { Clause antecedent = rule.NextAntecedent(); if (!m_wm.IsFact(antecedent)) { if (m_wm.IsNotFact(antecedent)) //conflict with memory { goal_reached = false; break; } else if (IsFact(antecedent, unproved_conditions)) //deduce to be a fact { m_wm.AddFact(antecedent); } else //deduce to not be a fact { goal_reached = false; break; } } } if (goal_reached) { conclusion = rule.getConsequent(); break; } } return(conclusion); }
//backward chain public Clause Infer(string goal_variable, List <Clause> unproved_conditions) { Clause conclusion = null; List <Rule> goal_stack = new List <Rule>(); foreach (Rule rule in m_rules) { Clause consequent = rule.getConsequent(); if (consequent.Variable == goal_variable) { goal_stack.Add(rule); } } foreach (Rule rule in goal_stack) { rule.FirstAntecedent(); bool goal_reached = true; while (rule.HasNextAntecedents()) { Clause antecedent = rule.NextAntecedent(); if (!m_wm.IsFact(antecedent)) { if (m_wm.IsNotFact(antecedent)) //conflict with memory { goal_reached = false; break; } else if (IsFact(antecedent, unproved_conditions)) //deduce to be a fact { string facts = string.Empty; foreach (var fact in m_wm._facts) { facts += $" {fact}"; } JustificationSingleton.WriteLine($"{facts}->{antecedent}\n\n"); m_wm.AddFact(antecedent); } else //deduce to not be a fact { goal_reached = false; break; } } } if (goal_reached) { conclusion = rule.getConsequent(); string facts = string.Empty; foreach (var fact in m_wm._facts) { facts += $" {fact}"; } JustificationSingleton.WriteLine($"{facts}->{conclusion}\n"); break; } } return(conclusion); }