public void AddRule(Rule rule) { _ruleSet.Add(rule); }
private bool CheckRule(Rule rule) { var arg = string.Empty; return CheckPattern(rule, ref arg) && FireRule(rule, arg); }
private bool FireRule(Rule rule, string arg) { var retval = false; var newCons = string.Empty; foreach(var walker in rule.Consequents) { var terms = GetTerms(walker.Element); switch (terms[0]) { case "(add": ConstructElement(ref newCons, terms[1], arg); retval = PerformAddCommand(newCons); break; case "(delete": ConstructElement(ref newCons, terms[1], arg); retval = PerformDeleteCommand(newCons); break; case "(disable-rule": rule.IsActive = false; retval = true; break; case "(print": retval = PerformPrintCommand(terms[1]); break; case "(enable-timer": retval = PerformEnableCommand(walker.Element); break; case "(quit": EndRun = true; break; } } return retval; }
private bool CheckPattern(Rule rule, ref string arg) { var found = false; var chain = new Stack<MemoryElement>(); foreach (var terms in rule.Antecedents.Select(antecedent => GetTerms(antecedent.Element))) { if (string.IsNullOrEmpty(terms[1])) { throw new InvalidOperationException("Argument can't be null!"); } /* If the antecedent element is variable, find the matches * in the working memory and store the matched terms. */ if (terms[1][0] != '?') continue; for (var i = 0; i < _memoryStore.Length; i++) { if (!_memoryStore[i].IsActive) continue; var wmTerms = GetTerms(_memoryStore[i].Element); if (!terms[0].Equals(wmTerms[0])) continue; var newElement = new MemoryElement { Element = wmTerms[1] }; chain.Push(newElement); } } /* Now that we have the replacement strings, walk through the rules trying * the replacement string when necessary. */ do { //var curRule = rule.Antecedent; string[] terms = null; foreach(var curRule in rule.Antecedents) { terms = GetTerms(curRule.Element); if (terms[0].IndexOf("(true", StringComparison.Ordinal) == 0) { found = true; break; } if ((terms[1][0] == '?') && (chain.Count > 0)) { terms[1] = chain.Peek().Element; } found = SearchWorkingMemory(terms[0], terms[1]); if (!found) break; } if (found) { /* Cleanup the replacement string chain */ arg = terms[1]; chain.Clear(); break; } if(chain.Count > 0 ) { chain.Pop(); } } while (chain.Count > 0); return found; }