This class allows queries to prolog.

A query can be created by a string or by constructing compound terms see Constructors for details.

All resources an terms created by a query are reclaimed by Dispose(). It is recommended to build a query in a scope.

There are four possible opportunities to query Prolog

Query typeDescription A static callTo ask prolog for a proof. Return only true or false. A PlCallQuery(string)To get the first result of a goal Construct a PlQuery object by a string.The most convenient way. Construct a PlQuery object by compound terms.The most flexible and fast (runtime) way.

For examples see PlQuery(string) and PlQuery(string, PlTermV)

The query will be opened by NextSolution() and will be closed if NextSolution() return false.

Inheritance: IDisposable
 public int Get_Category(string Categoria)
 {
     var q = new PlQuery("categoria(X,"+Categoria+",Y,Z)");
     foreach (PlQueryVariables v in q.SolutionVariables)
     {
         return Convert.ToInt32(v["Z"].ToString());
     }
     return 0;
 }
        public string Get_MachineAnswer(string Estado)
        {
            var Machine = new PlQuery("jugandoconlamaquina("+Estado+",X)");
            foreach (PlQueryVariables v in Machine.SolutionVariables)
            {

                return v["X"].ToString();
            }
            return "entre aqui";
        }
Exemple #3
0
 public void testProlog()
 {
     //Environment.SetEnvironmentVariable("SWI_HOME_DIR", @"C:\Programme\pl\");
     File.Exists(@"C:\Programme\pl\boot32.prc");
     PlEngine.Initialize(new String[] { "" });
     Console.Out.WriteLine(PlQuery.PlCall(@"consult('Prolog\\Streets.pl')"));
     PlQuery q = new PlQuery("street(X,Y,Z,U,V).");
     foreach (PlTermV s in q.Solutions)
         Console.WriteLine(s[1].ToString());
     PlEngine.PlCleanup();
 }
 public void SetValue(ICollectionRequester requester, string name, object value)
 {
     PrologCLR.InvokeFromC(
         () =>
             {
                 if (IsEmpty(Setter)) return false;
                 var plVar = PlTerm.PlVar();
                 var query = new PlQuery(Module, Setter,
                                         new PlTermV(PrologCLR.ToProlog(requester), PlTerm.PlString(NameSpace), PlTerm.PlString(name),
                                                     PrologCLR.ToProlog(value)));
                 while (query.NextSolution())
                 {
                     
                 }
                 return true;
             }, DiscardFrames);
 }
 //Load prolog file from hard disk
 public void Load_file(string s)
 {
     s = s.Replace("\\", "//");
     s = "consult('" + s + "')";
     string query = s.Replace("\\", "//");
     //string[] p = { "-q", "-f", query };
     //PlEngine.Initialize(p);
     try
     {
         PlQuery q = new PlQuery(query);
         Assert.IsTrue(q.NextSolution());
     }
     catch (SbsSW.SwiPlCs.Exceptions.PlException e)
     {
         System.Windows.Forms.MessageBox.Show(e.ToString(), "Error");
     }
 }
        public string Answer(string Categoria,string Pregunta,string Answer)
        {
            var q = new PlQuery("respuesta("+Pregunta+","+Categoria+",Y,X)");
                foreach (PlQueryVariables v in q.SolutionVariables)
                {

                    if(Answer.Equals(v["Y"].ToString()))
                    {
                        return "correcto";
                    }
                    else
                    {
                        return "incorrecta";
                    }
                }

            return "Entre aqui";
        }
Exemple #7
0
        private string mHumanSign; // the sign of the human player ('x' or 'o')

        #endregion Fields

        #region Constructors

        /// <summary>
        /// constructor.
        /// </summary>
        /// <param name="path">The prolog file path</param>
        /// <param name="humanStart"><b>True</b> is the human player does the first move, otherwise <b>false</b>.</param>
        /// <param name="difficulty">The difficulty lever of the computer player (2-5)</param>
        public GameEngine(string path, bool humanStart, int difficulty)
        {
            PlEngine.Initialize(new string[] { "-q", "-f", path });

            mDifficulty = difficulty;

            mHumanSign = "o";
            mComputerSign = "x";

            PlQuery.PlCall("assert", new PlTermV(new PlTerm(string.Format("min_to_move({0} / _)", mHumanSign))));
            PlQuery.PlCall("assert", new PlTermV(new PlTerm(string.Format("max_to_move({0} / _)", mComputerSign))));

            using (PlQuery q = new PlQuery("init(B)"))
            {
                string b = q.SolutionVariables.First()["B"].ToString();
                mBoard = BoardString(b);
            }
        }
Exemple #8
0
        public static void Main(string[] args0)
        {
            PrologCLR.PingThreadFactories();
            bool demo = false;
            PrologCLR.SetupProlog();

            if (demo)
            {
                PrologCLR.DoQuery("asserta(fff(1))");
                PrologCLR.DoQuery("asserta(fff(9))");
                PrologCLR.DoQuery("nl");
                PrologCLR.DoQuery("flush");

                PrologCLR.PlAssert("father(martin, inka)");
                if (!Embedded.PlCsDisabled)
                {
                    PlQuery.PlCall("assert(father(uwe, gloria))");
                    PlQuery.PlCall("assert(father(uwe, melanie))");
                    PlQuery.PlCall("assert(father(uwe, ayala))");
                    using (PlQuery q = new PlQuery("father(P, C), atomic_list_concat([P,' is_father_of ',C], L)"))
                    {
                        foreach (PlTermV v in q.Solutions)
                            PrologCLR.ConsoleTrace(PrologCLR.ToCSString(v));

                        foreach (PlQueryVariables v in q.SolutionVariables)
                            PrologCLR.ConsoleTrace(v["L"].ToString());

                        PrologCLR.ConsoleTrace("all child's from uwe:");
                        q.Variables["P"].Unify("uwe");
                        foreach (PlQueryVariables v in q.SolutionVariables)
                            PrologCLR.ConsoleTrace(v["C"].ToString());
                    }
                    //PlQuery.PlCall("ensure_loaded(library(thread_util))");
                    //Warning: [Thread 2] Thread running "thread_run_interactor" died on exception: thread_util:attach_console/0: Undefined procedure: thread_util:win_open_console/5
                    //PlQuery.PlCall("interactor");
                    //Delegate Foo0 = foo0;
                    PrologCLR.RegisterPLCSForeigns();
                }

                PrologCLR.PlAssert("tc2:-foo2(X,Y),writeq(f(X,Y)),nl,X=5");
                PrologCLR.PlAssert("tc3:-foo3(X,Y,Z),Z,writeln(f(X,Y,Z)),X=5");
            }
        }
 public IEnumerable<string> SettingNames(ICollectionRequester requester, int depth)
 {
     return PrologCLR.InvokeFromC(
         () =>
             {
                 if (IsEmpty(KeyGetter)) return null;
                 List<string> names = new List<string>();
                 var plVar = PlTerm.PlVar();
                 var query = new PlQuery(Module, KeyGetter,
                                         new PlTermV(PrologCLR.ToProlog(requester), PlTerm.PlString(NameSpace),
                                                     plVar));
                 while (query.NextSolution())
                 {
                     string res = (string) query.Args[2];
                     if (!names.Contains(res)) names.Add(res);
                 }
                 return names.ToArray();
             }, DiscardFrames);
 }        
Exemple #10
0
    public int[] CarregaGrafo(int id)
    {
        IList<int> resultados = new List<int>();
        string line = "";
        try
        {
            Environment.SetEnvironmentVariable("SWI_HOME_DIR", @"C:\Program Files\swipl\");
            String[] param = { "-q", "-f", "C:\\PredicadosProlog\\odbc.pl" };
            PlEngine.Initialize(param);
            using (PlQuery q = new PlQuery("nodos(" + id + ", X,Y,Z)"))
            {
                foreach (PlQueryVariables v in q.SolutionVariables)
                {
                    Console.Clear();
                    Console.WriteLine(v["X"].ToString());
                    line = v["X"].ToString();
                    if (line != null)
                        resultados.Add(Convert.ToInt32(line));

                    Console.WriteLine(v["Y"].ToString());
                    line = v["Y"].ToString();
                    if (line != null)
                        resultados.Add(Convert.ToInt32(line));

                    Console.WriteLine(v["Z"].ToString());
                    line = v["Z"].ToString();
                    if (line != null)
                        resultados.Add(Convert.ToInt32(line));
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            PlEngine.PlCleanup();
        }
        return resultados.ToArray();
    }
        // Prosessing a query
        public string Query(string s)
        {
            s.Trim();
            Regex r = new Regex(@"[A-Z_][a-zA-Z_]*");
            MatchCollection matches = r.Matches(s);
            string result = "";
            try
            {
                PlQuery q = new PlQuery(s);
                bool HasSolution = false;
                //q.ToList();
                foreach (PlQueryVariables v in q.SolutionVariables)
                {

                    HasSolution = true;
                    //foreach (Match match in matches)
                    //{
                        try
                        {
                            result += v["X"].ToString() + " ; ";
                        }
                        catch (ArgumentException e)
                        {
                            continue;
                        }
                    //}
                }

                if (matches.Count == 0)
                    return HasSolution ? "true" : "false";
                return result;
            }
            catch (SbsSW.SwiPlCs.Exceptions.PlException ex)
            {
                //return "Error query: " + ex.Message;
                return "";
            }
        }
Exemple #12
0
        static void Main(string[] args)
        {
            //Environment.SetEnvironmentVariable("SWI_HOME_DIR", @"c:\Program Files\swipl\");
            if (!PlEngine.IsInitialized)
            {
                //String[] param = { "-q" };  // suppressing informational and banner messages
                String[] param = { "-q", "-f", AppDomain.CurrentDomain.BaseDirectory + "ex_genitor.pl" };
                PlEngine.Initialize(param);

                PlQuery q1 = new PlQuery("ancestral(X, josé)");
                foreach (PlQueryVariables vars in q1.SolutionVariables)
                {
                    for (int i = 0; i < q1.VariableNames.Count; i++)
                    {
                        Console.Write(q1.VariableNames[i].ToString() + " -> " + (string)vars[q1.VariableNames[i]] + "\t");

                    }
                    Console.WriteLine();
                }
                PlEngine.PlCleanup();
            }

            Console.ReadLine();
        }
 public string Get_Question(string Name_Category, string puntaje)
 {
     List<string>  Question = new List<string>();
     var q = new PlQuery("pregunta(X,"+Name_Category+","+puntaje+")");
     foreach(PlQueryVariables v in q.SolutionVariables)
     {
         return v["X"].ToString();
     }
     return null;
 }
 //get logs
 private void CheckHistory_Thread()
 {
     PlEngine.PlThreadAttachEngine();
     while (running)
     {
         using (PlQuery query = new PlQuery("getLog(Log)"))
         {
             PlTermV termV = query.Solutions.FirstOrDefault();
             if (termV.Size != 0)
             {
                 History = termV[0].ToListString();
             }
         }
         Thread.Sleep(250);
     }
     PlEngine.PlThreadDestroyEngine();
 }
 //get stones
 private void CheckStones_Thread()
 {
     PlEngine.PlThreadAttachEngine();
     while (running)
     {
         using (PlQuery query = new PlQuery("getStoneList(Stones)"))
         {
             PlTermV termV = query.Solutions.FirstOrDefault();
             if (termV.Size != 0)
             {
                 Stones = termV[0].ToList().Select((t) => new Stone(t)).ToList();
             }
         }
         Thread.Sleep(250);
     }
     PlEngine.PlThreadDestroyEngine();
 }
        public int Point_Answer(string Categoria, string Pregunta)
        {
            var q = new PlQuery("respuesta(" + Pregunta + "," + Categoria + ",Y,X)");
            foreach (PlQueryVariables v in q.SolutionVariables)
            {

                    return P_Score = Convert.ToInt32(v["X"].ToString());

            }

            return 0;
        }
 //moves a stone (destination is propably not the real destination; real destination is return value)
 private Field MoveStone(Field source, Field destination)
 {
     string direction = GetDirection(source, destination);
     PlQuery query = new PlQuery("moveStone", new PlTermV(source.ToTerm(), new PlTerm(direction), new PlTerm("NewDestination")));
     PlTermV termV = query.Solutions.FirstOrDefault();
     return termV.Size == 0 ? default(Field) : new Field(termV[2]);
 }
Exemple #18
0
        /// <summary>
        /// Make the human move on the board
        /// </summary>
        /// <param name="fromL">From line</param>
        /// <param name="fromC">From column</param>
        /// <param name="toL">To line</param>
        /// <param name="toC">To column</param>
        /// <returns><b>True</b> if this is a valid move, otherwise <b>False</b>.</returns>
        public bool PlayHuman(int fromL, int fromC, int toL, int toC)
        {
            string board = StringBoard(mBoard);
            string query = string.Format("move({0}, {1}, {2}, {3}, {4}, NewBoard)", board, fromL, fromC, toL, toC);

            using (PlQuery q = new PlQuery(query))
            {
                if (q.SolutionVariables.Count() > 0)
                {
                    PlTerm newBoard = q.SolutionVariables.First()["NewBoard"];
                    string result = newBoard[0].ToString();
                    mBoard = BoardString(result);
                    return true;
                }
            }
            return false;
        }
Exemple #19
0
        //[MTAThread]
        public static void Main_Was(string[] args0)
        {
            PingThreadFactories();
            bool demo = false;
            SetupProlog();

            if (demo)
            {
                DoQuery("asserta(fff(1))");
                DoQuery("asserta(fff(9))");
                DoQuery("nl");
                DoQuery("flush");

                PlAssert("father(martin, inka)");
                if (!Embedded.PlCsDisabled)
                {
                    PlQuery.PlCall("assert(father(uwe, gloria))");
                    PlQuery.PlCall("assert(father(uwe, melanie))");
                    PlQuery.PlCall("assert(father(uwe, ayala))");
                    using (PlQuery q = new PlQuery("father(P, C), atomic_list_concat([P,' is_father_of ',C], L)"))
                    {
                        foreach (PlTermV v in q.Solutions)
                            ConsoleTrace(ToCSString(v));

                        foreach (PlQueryVariables v in q.SolutionVariables)
                            ConsoleTrace(v["L"].ToString());

                        ConsoleTrace("all child's from uwe:");
                        q.Variables["P"].Unify("uwe");
                        foreach (PlQueryVariables v in q.SolutionVariables)
                            ConsoleTrace(v["C"].ToString());
                    }
                    //PlQuery.PlCall("ensure_loaded(library(thread_util))");
                    //Warning: [Thread 2] Thread running "thread_run_interactor" died on exception: thread_util:attach_console/0: Undefined procedure: thread_util:win_open_console/5
                    //PlQuery.PlCall("interactor");
                    //Delegate Foo0 = foo0;
                    RegisterPLCSForeigns();
                }

                PlAssert("tc2:-foo2(X,Y),writeq(f(X,Y)),nl,X=5");
                PlAssert("tc3:-foo3(X,Y,Z),Z,writeln(f(X,Y,Z)),X=5");
            }

            #if USE_IKVM
             //   ClassFile.ThrowFormatErrors = false;
            libpl.NoToString = true;
            //SafelyRun((() => PlCall("jpl0")));
            //SafelyRun((() => DoQuery(new Query(new org.jpl7.Atom("jpl0")))));
            libpl.NoToString = false;
              //      ClassFile.ThrowFormatErrors = true;
            #endif
            if (args0.Length > 0)
            {
                int i = 0;
                foreach (var s in args0)
                {
                    if (s == "-f")
                    {
                        string s1 = args0[i + 1];
                        args0[i + 1] = "['" + s1 + "']";
                        continue;
                    }
                    PlCall(s);
                    i++;
                }
            }
            if (!Embedded.JplDisabled)
            {
            #if USE_IKVM
                var run = new org.jpl7.Atom("prolog");
                while (!Embedded.IsHalted) SafelyRun(() => DoQuery(new org.jpl7.Query(run)));
            #endif
            }
            else
            {
                if (!Embedded.PlCsDisabled)
                    // loops on exception
                    while (!SafelyRun(() => libpl.PL_toplevel())) ;
            }

            ConsoleTrace("press enter to exit");
            Console.ReadLine();
            SafelyRun(() => PlEngine.PlCleanup());

            ConsoleTrace("finshed!");
        }
 public void SetValue(ICollectionRequester requester, string name, object value)
 {
     PrologCLR.InvokeFromC(
         () =>
         {
             PlTerm callback = AllCallbacks.Args[1];
             if (IsEmpty(callback)) return false;
             var plVar = PlTerm.PlVar();
             var query = new PlQuery("call",
                                     new PlTermV(callback, PlTerm.PlString(NameSpace), PlTerm.PlString(name),
                                                 PrologCLR.ToProlog(value)));
             return query.NextSolution();
         }, DiscardFrames);
 }
        public BotVarProviderCallN(PlTerm nameSpace, PlTerm getter, PlTerm setter, PlTerm keyGetter)
        {

            uint fid = libpl.PL_open_foreign_frame();
            NameSpace = nameSpace.Name;
            AllCallbacks = new PlQuery("call", new PlTermV(getter, setter, keyGetter));
            AllCallbacks.EnsureQUID();
            GCHandle.Alloc(AllCallbacks);
            GCHandle.Alloc(this);
        }
Exemple #22
0
        //TODO: <umstellen auf PlQuery(string)/>
        /// <summary>
        /// <para>NOTE:will be changed in the near future.</para>
        /// return the solution of a query which is called once by call
        /// Throw an ArgumentException if there is no or more than one variable in the goal
        /// </summary>
        /// <param name="goal">a goal with *one* variable</param>
        /// <returns>the bound variable of the first solution</returns>
        public static PlTerm PlCallQuery(string goal)
        {
            PlTerm retVal;
            PlQuery q = new PlQuery(goal);
            {
                // find the variable or throw an exception
                PlTerm ? t = null;
                for (int i = 0; i < q._av.Size; i++)
                {
                    if (q._av[i].IsVar)
                    {
                        if ((object)t == null)
                        {
                            t = new PlTerm(q._av[i].TermRef);
                        }
                        else
                            throw new ArgumentException("More than one Variable in " + goal);
                    }
                }
                if ((object)t == null)
                    throw new ArgumentException("No Variable found in " + goal);

                if (q.NextSolution())
                {
                    retVal = (PlTerm)t;
                }
                else
                    retVal = new PlTerm();    // null
            }
            q.Free(false);
            return retVal;
        }
Exemple #23
0
#pragma warning restore 1573
        /// <inheritdoc cref="PlCall(string, PlTermV)" />
        /// <summary>Call a goal once.</summary>
        /// <example>
        /// <code>
        ///      Assert.IsTrue(PlQuery.PlCall("is_list([a,b,c,d])"));
        /// </code>
        /// <code>
        ///      Assert.IsTrue(PlQuery.PlCall("consult('some_file_name')"));
        /// </code>
        /// </example>
        /// <param name="goal">The complete goal as a string</param>
        public static bool PlCall(string goal)
        {
            // TODO: change to use PlTerm(text) or PlCompound(string)
            // TODO: <weiterre tests z.b. mehrere goals/>
            bool bRet = false;
            PlQuery q = new PlQuery("call", new PlTermV(PlTerm.PlCompound(goal)));
            bRet = q.NextSolution();
            q.Free(true);
            return bRet;
        }
Exemple #24
0
#pragma warning disable 1573
        /// <inheritdoc cref="PlCall(string, PlTermV)" />
        /// <summary>As <see cref="PlCall(string, PlTermV)"/> but locating the predicate in the named module.</summary>
        /// <param name="module">locating the predicate in the named module.</param>
        public static bool PlCall(string module, string predicate, PlTermV args)
        {
            bool bRet = false;
            PlQuery q = new PlQuery(module, predicate, args);
            bRet = q.NextSolution();
            q.Free(false);
            return bRet;
        }
Exemple #25
0
        /// <summary>
        /// Make the computer move on the board
        /// </summary>
        public void PlayComputer()
        {
            PlEngine.PlThreadAttachEngine();
            string board = StringBoard(mBoard);

            string query = string.Format(@"alphabeta({0}/{1}, -100, 100, NewBoard, Temp, {2})", mComputerSign, board, mDifficulty);

            using (PlQuery q = new PlQuery(query))
            {
                PlTerm newBoard = q.SolutionVariables.First()["NewBoard"];
                string result = newBoard[0].ToString();
                string next = result.Substring(0, 1);
                string b = result.Substring(2);
                mBoard = BoardString(b);
            }
            PlEngine.PlThreadDestroyEngine();
        }
 public ICollection GetGroup(ICollectionRequester requester, string name)
 {
     return PrologCLR.InvokeFromC(
         () =>
             {
                 if (IsEmpty(Getter)) return null;
                 var plVar = PlTerm.PlVar();
                 List<object> results = new List<object>();
                 var query = new PlQuery(Module, Getter,
                                         new PlTermV(PrologCLR.ToProlog(requester), PlTerm.PlString(NameSpace), PlTerm.PlString(name),
                                                     plVar));
                 while (query.NextSolution())
                 {
                     object res = PrologCLR.GetInstance(query.Args[3]);
                     if (!results.Contains(res)) results.Add(res);
                 }
                 return results.Count == 0 ? null : results;
             }, DiscardFrames);
 }
Exemple #27
0
#pragma warning disable 1573
        /// <inheritdoc cref="PlQuery(string)" />
        /// <summary>locating the predicate in the named module.</summary>
        /// <param name="module">locating the predicate in the named module.</param>
        public PlQuery(string module, string goal)
        {
            _module       = module;
            _query_string = goal;
            //_query_string = "(" + _query_string + ")";
            if (!_query_string.EndsWith(".", StringComparison.Ordinal))
            {
                _query_string += ".";
            }
            _query_string += Environment.NewLine;

            // redirect read stream
            DelegateStreamReadFunction old_read_function = PlEngine._function_read;
            DelegateStreamReadFunction rf = new DelegateStreamReadFunction(Sread);

            if (PrologCLR.RedirectStreams)
            {
                PlEngine.SetStreamFunctionRead(PlStreamType.Input, rf);
            }

            try
            {
                // call read_term(Term_of_query_string, [variable_names(VN)]).
                PlTerm term               = PlTerm.PlVar();
                PlTerm option_list        = PlTerm.PlVar();
                PlTerm variablenames_list = PlTerm.PlVar();
                PlTerm l = PlTerm.PlTail(option_list);
                l.Append(PlTerm.PlCompound("variable_names", variablenames_list));
                l.Close();
                PlTermV args = new PlTermV(term, option_list);
                // NOTE: read/1 needs a dot ('.') at the end
                if (!PlQuery.PlCall("read_term", args))
                {
                    throw new PlLibException("PlCall read_term fails! goal:" + _query_string);
                }

                // restore stream function
                if (PrologCLR.RedirectStreams)
                {
                    PlEngine.SetStreamFunctionRead(PlStreamType.Input, old_read_function);
                }

                // set list of variables and variable_names into _queryVariables
                foreach (PlTerm t in variablenames_list.ToList())
                {
                    // t[0]='=' , t[1]='VN', t[2]=_G123
                    _queryVariables.Add(new PlQueryVar(t[1].ToString(), t[2]));
                }

                // Build the query
                _name = term.Name;

                // is ok e.g. for listing/0.
                // Check.Require(term.Arity > 0, "PlQuery(PlTerm t): t.Arity must be greater than 0.");
                _av = new PlTermV(term.Arity);
                for (int index = 0; index < term.Arity; index++)
                {
                    if (0 == libpl.PL_get_arg(index + 1, term.TermRef, _av[index].TermRef))
                    {
                        throw new PlException("PL_get_arg in PlQuery " + term.ToString());
                    }
                }
            }
#if _DEBUG
            catch (Exception ex)
            {
                PrologCLR.ConsoleTrace(ex.Message);
            }
#endif
            finally
            {
                // NBT
            }
        }
 //check for more hits
 private IEnumerable<Field> MoreHitsPossible(Field source)
 {
     PlQuery query = new PlQuery("areMoreHitsPossible", new PlTermV(source.ToTerm(), new PlTerm("Hits")));
     PlTermV termV = query.Solutions.FirstOrDefault();
     if (termV.Size == 0)
         return new List<Field>();
     IEnumerable<PlTerm> list = termV[1].ToList();
     return list.Select<PlTerm, Field>((t) => new Field(t)).ToList();
 }