BagofAnswers.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. /*
  2. * Copyright (C) 2007-2008, Jeff Thompson
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * * Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * * Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * * Neither the name of the copyright holder nor the names of its contributors
  15. * may be used to endorse or promote products derived from this software
  16. * without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  22. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  23. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  24. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  25. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  26. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  27. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  28. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. using System;
  31. using System.Collections;
  32. using System.Collections.Generic;
  33. namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
  34. {
  35. /// <summary>
  36. /// A BagofAnswers holds answers for bagof and setof.
  37. /// </summary>
  38. public class BagofAnswers
  39. {
  40. private object _template;
  41. private Variable[] _freeVariables;
  42. private Dictionary<object[], List<object>> _bagForFreeVariables;
  43. private List<object> _findallBagArray;
  44. private static TermArrayEqualityComparer _termArrayEqualityComparer =
  45. new TermArrayEqualityComparer();
  46. /// <summary>
  47. /// To get the free variables, split off any existential qualifiers from Goal such as the X in
  48. /// "X ^ f(Y)", get the set of unbound variables in Goal that are not qualifiers, then remove
  49. /// the unbound variables that are qualifiers as well as the unbound variables in Template.
  50. /// </summary>
  51. /// <param name="Template"></param>
  52. /// <param name="Goal"></param>
  53. public BagofAnswers(object Template, object Goal)
  54. {
  55. _template = Template;
  56. // First get the set of variables that are not free variables.
  57. List<Variable> variableSet = new List<Variable>();
  58. YP.addUniqueVariables(Template, variableSet);
  59. object UnqualifiedGoal = YP.getValue(Goal);
  60. while (UnqualifiedGoal is Functor2 && ((Functor2)UnqualifiedGoal)._name == Atom.HAT)
  61. {
  62. YP.addUniqueVariables(((Functor2)UnqualifiedGoal)._arg1, variableSet);
  63. UnqualifiedGoal = YP.getValue(((Functor2)UnqualifiedGoal)._arg2);
  64. }
  65. // Remember how many non-free variables there are so we can find the unique free variables
  66. // that are added.
  67. int nNonFreeVariables = variableSet.Count;
  68. YP.addUniqueVariables(UnqualifiedGoal, variableSet);
  69. int nFreeVariables = variableSet.Count - nNonFreeVariables;
  70. if (nFreeVariables == 0)
  71. {
  72. // There were no free variables added, so we won't waste time with _bagForFreeVariables.
  73. _freeVariables = null;
  74. _findallBagArray = new List<object>();
  75. }
  76. else
  77. {
  78. // Copy the free variables.
  79. _freeVariables = new Variable[nFreeVariables];
  80. for (int i = 0; i < nFreeVariables; ++i)
  81. _freeVariables[i] = variableSet[i + nNonFreeVariables];
  82. _bagForFreeVariables = new Dictionary<object[], List<object>>(_termArrayEqualityComparer);
  83. }
  84. }
  85. public void add()
  86. {
  87. if (_freeVariables == null)
  88. // The goal has bound the values in _template but we don't bother with _freeVariables.
  89. _findallBagArray.Add(YP.makeCopy(_template, new Variable.CopyStore()));
  90. else
  91. {
  92. // The goal has bound the values in _template and _freeVariables.
  93. // Find the entry for this set of _freeVariables values.
  94. object[] freeVariableValues = new object[_freeVariables.Length];
  95. for (int i = 0; i < _freeVariables.Length; ++i)
  96. freeVariableValues[i] = YP.getValue(_freeVariables[i]);
  97. List<object> bagArray;
  98. if (!_bagForFreeVariables.TryGetValue(freeVariableValues, out bagArray))
  99. {
  100. bagArray = new List<object>();
  101. _bagForFreeVariables[freeVariableValues] = bagArray;
  102. }
  103. // Now copy the template and add to the bag for the freeVariables values.
  104. bagArray.Add(YP.makeCopy(_template, new Variable.CopyStore()));
  105. }
  106. }
  107. /// <summary>
  108. /// For each result, unify the _freeVariables and unify bagArrayVariable with the associated bag.
  109. /// </summary>
  110. /// <param name="bagArrayVariable">this is unified with the List<object> of matches for template that
  111. /// corresponds to the bindings for freeVariables. Be very careful: this does not unify with a Prolog
  112. /// list.</param>
  113. /// <returns></returns>
  114. public IEnumerable<bool> resultArray(Variable bagArrayVariable)
  115. {
  116. if (_freeVariables == null)
  117. {
  118. // No unbound free variables, so we only filled one bag. If empty, bagof fails.
  119. if (_findallBagArray.Count > 0)
  120. {
  121. // disable warning: don't see how we can code this differently short
  122. // of rewriting the whole thing
  123. #pragma warning disable 0168
  124. foreach (bool l1 in bagArrayVariable.unify(_findallBagArray))
  125. yield return false;
  126. #pragma warning restore 0168
  127. }
  128. }
  129. else
  130. {
  131. foreach (KeyValuePair<object[], List<object>> valuesAndBag in _bagForFreeVariables)
  132. {
  133. // disable warning: don't see how we can code this differently short
  134. // of rewriting the whole thing
  135. #pragma warning disable 0168
  136. foreach (bool l1 in YP.unifyArrays(_freeVariables, valuesAndBag.Key))
  137. {
  138. foreach (bool l2 in bagArrayVariable.unify(valuesAndBag.Value))
  139. yield return false;
  140. }
  141. #pragma warning restore 0168
  142. // Debug: Should we free memory of the answers already returned?
  143. }
  144. }
  145. }
  146. /// <summary>
  147. /// For each result, unify the _freeVariables and unify Bag with the associated bag.
  148. /// </summary>
  149. /// <param name="Bag"></param>
  150. /// <returns></returns>
  151. public IEnumerable<bool> result(object Bag)
  152. {
  153. Variable bagArrayVariable = new Variable();
  154. // disable warning: don't see how we can code this differently short
  155. // of rewriting the whole thing
  156. #pragma warning disable 0168
  157. foreach (bool l1 in resultArray(bagArrayVariable))
  158. {
  159. foreach (bool l2 in YP.unify(Bag, ListPair.make((List<object>)bagArrayVariable.getValue())))
  160. yield return false;
  161. }
  162. #pragma warning restore 0168
  163. }
  164. /// <summary>
  165. /// For each result, unify the _freeVariables and unify Bag with the associated bag which is sorted
  166. /// with duplicates removed, as in setof.
  167. /// </summary>
  168. /// <param name="Bag"></param>
  169. /// <returns></returns>
  170. public IEnumerable<bool> resultSet(object Bag)
  171. {
  172. Variable bagArrayVariable = new Variable();
  173. // disable warning: don't see how we can code this differently short
  174. // of rewriting the whole thing
  175. #pragma warning disable 0168
  176. foreach (bool l1 in resultArray(bagArrayVariable))
  177. {
  178. List<object> bagArray = (List<object>)bagArrayVariable.getValue();
  179. YP.sortArray(bagArray);
  180. foreach (bool l2 in YP.unify(Bag, ListPair.makeWithoutRepeatedTerms(bagArray)))
  181. yield return false;
  182. }
  183. #pragma warning restore 0168
  184. }
  185. public static IEnumerable<bool> bagofArray
  186. (object Template, object Goal, IEnumerable<bool> goalIterator, Variable bagArrayVariable)
  187. {
  188. BagofAnswers bagOfAnswers = new BagofAnswers(Template, Goal);
  189. // disable warning: don't see how we can code this differently short
  190. // of rewriting the whole thing
  191. #pragma warning disable 0168
  192. foreach (bool l1 in goalIterator)
  193. bagOfAnswers.add();
  194. #pragma warning restore 0168
  195. return bagOfAnswers.resultArray(bagArrayVariable);
  196. }
  197. public static IEnumerable<bool> bagof
  198. (object Template, object Goal, IEnumerable<bool> goalIterator, object Bag)
  199. {
  200. BagofAnswers bagOfAnswers = new BagofAnswers(Template, Goal);
  201. // disable warning: don't see how we can code this differently short
  202. // of rewriting the whole thing
  203. #pragma warning disable 0168
  204. foreach (bool l1 in goalIterator)
  205. bagOfAnswers.add();
  206. #pragma warning restore 0168
  207. return bagOfAnswers.result(Bag);
  208. }
  209. public static IEnumerable<bool> setof
  210. (object Template, object Goal, IEnumerable<bool> goalIterator, object Bag)
  211. {
  212. BagofAnswers bagOfAnswers = new BagofAnswers(Template, Goal);
  213. // disable warning: don't see how we can code this differently short
  214. // of rewriting the whole thing
  215. #pragma warning disable 0168
  216. foreach (bool l1 in goalIterator)
  217. bagOfAnswers.add();
  218. #pragma warning restore 0168
  219. return bagOfAnswers.resultSet(Bag);
  220. }
  221. /// <summary>
  222. /// A TermArrayEqualityComparer implements IEqualityComparer to compare two object arrays using YP.termEqual.
  223. /// </summary>
  224. private class TermArrayEqualityComparer : IEqualityComparer<object[]>
  225. {
  226. public bool Equals(object[] array1, object[] array2)
  227. {
  228. if (array1.Length != array2.Length)
  229. return false;
  230. for (int i = 0; i < array1.Length; ++i)
  231. {
  232. if (!YP.termEqual(array1[i], array2[i]))
  233. return false;
  234. }
  235. return true;
  236. }
  237. public int GetHashCode(object[] array)
  238. {
  239. int hashCode = 0;
  240. for (int i = 0; i < array.Length; ++i)
  241. hashCode ^= array[i].GetHashCode();
  242. return hashCode;
  243. }
  244. }
  245. }
  246. }