Swicli.Library
This finds things like op_Implicit/op_Explicition to
?- cliNewArray(long,10,Out),cliToString(Out,Str).
10 or [10] or [10,2]
Tagged ref to the array
Construct an array of some type
The parent array type .. not the Element type
Returns the Type when denoated by a 'namespace.type' (usefull for static instance specification)
if a @C#234234 the type of the object unless its a a class
c(a) => System.Char "sdfsdf" => System.String uint(5) => System.UInt32
instanceMaybe maybe Null.. it is passed in so the method code doesn't have to call GetInstance again
on classOrInstance
?- current_bot(Obj),cli_add_event_handler(Obj,'EachSimEvent',c(A,format(user_error,'EV = ~q.~n',[A])),Out).
this is just stuffed with a random MethodInfo
0 = SetValue
1 = Count
2 = add/append
3 = GetValue
4 = removeValue
5 = removeAll
6 = cliAddElementGeneric
7 = cliSetElementGeneric
Create a Event Handler with a ResetEvent
Add another event to be waited on
Block until ResetEvent occures and run the prolog code.. if it fails.. wait again for the reset event
if over maxTime return time_limit_exceeded
1 ?- cliToString(-1,X).
X = "4294967295".
This is no longer needed since we use atom GC (maybe)
?- cliNew('java.lang.Long',[long],[44],Out),cliToString(Out,Str).
This after the SwiPrologDir and IKVMHome is set up will update the environment
cliLoadAssembly('SwiPlCs.dll').
cliLoadAssembly('Cogbot.exe').
?- cliAddAssemblySearchPath('.').
cliRemoveAssemblySearchPath('.').
Retreves the ClazzSpec Fields and Properties into a MemberSpecList
Retreves the clazzOrInstance Members into MemberSpec List
used by cli_memb/2
=Attempt to find assembly doc of member
FIX ME!!
[] = 'Item'
libpl
Does NOT work correct if engine is_initialised
int PL_is_initialised(int *argc, char ***argv)
a SWI-PROLOG IOSTREAM defined in spl-stream.h
int PL_foreign_control(control_t)
Extracts the type of call from the control argument.
The return values are described above.
Note: that the function should be prepared to handle the PL_CUTTED case and
Note: should be aware that the other arguments are not valid in this case.
long PL_foreign_context(control_t)
Extracts the context from the context argument.
In the call type is PL_FIRST_CALL the context value is 0L.
Otherwise it is the value returned by the last PL_retry() associated
with this goal (both if the call type is PL_REDO as PL_CUTTED).
void * PL_foreign_context_address(control_t)
Extracts an address as passed in by PL_retry_address().
void PL_retry(long)
The foreign function succeeds while leaving a choice point.
On backtracking over this goal the foreign function will be called again,
but the control argument now indicates it is a `Redo' call and the macro
PL_foreign_context() will return the handle passed via PL_retry().
This handle is a 30 bits signed value (two bits are used for status indication).
void PL_retry_address(void *)
As PL_retry(), but ensures an address as returned by malloc()
is correctly recovered by PL_foreign_context_address().
The standard SWI-Prolog streams ( inout output error )
0 - Sread_function.
1 - Swrite_function.
Flags that control for the foreign predicate parameters
SWI-Prolog Manual - 9.6.16 Querying Prolog.
The default value.
Return an integer holding the number of arguments given to Prolog from Unix.
Return a char ** holding the argument vector given to Prolog from Unix.
Read character from terminal.
Return a long, representing the maximal integer value represented by a Prolog integer.
Return a long, representing the minimal integer value.
Return a long, representing the version as 10,000 × M + 100 × m + p, where M is the major, m the minor version number and p the patch-level. For example, 20717 means 2.7.17
Return the maximum number of threads that can be created in this version. Return values of PL_thread_self() are between 0 and this number.
Return the default stream encoding of Prolog (of type IOENC).
Get amount of user CPU time of the process in milliseconds.
Represents one variable of a Query result.
The name of a variable in a Query
The ManagedObject (PlTerm) of a variable in a Query
Represents the set variables of a Query if it was created from a string.
This class is also used to represent the results of a PlQuery after or was called.
This sample shows both is used to unify the variables of two nested queries
and the result
Returns the number of elements in the sequence. (Defined by Enumerable of List<PlQueryVar>.)
Gets the of the given variable name or throw an ArgumentException.
The name of the variable
The PlTerm (value) of the variable
Is thrown if the name is not the name of a variable.
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 . 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 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 and
The query will be opened by and will be closed if NextSolution() return false.
the list of prolog record's (the copies to store the variable bindings over backtracking)
Release all resources from the query
if true all is deleted
Discards the query, but does not delete any of the data created by the query if discardData is false.
It just invalidate qid, allowing for a new PlQuery object in this context.
see
if true all bindings of the query are destroyed
With these constructors a Prolog query can be created but not opened. To get the results see
A Query can be created from a string or by a name and PlTermV. The later is a native way and available for compatibility.
If a Query is created from a string representing arbitrary prolog text
the helper classes and comes into the game.
In this case the most convenient way to get the results is to use or .
For examples see .
With this constructor a query is created from a string.
Uppercase parameters are interpreted a variables but can't be nested in sub terms.
If you need a variable in a nested term use .
See the examples for details.
Muddy Waters sang:"I'am build for comfort, I ain't build for speed"
This sample shows a query with two variables.
And the same with named variables.
This sample shows what happens if the argument vector is used with compound terms.
And here how to get the results with named variables with compound terms.
A string for a prolog query
locating the predicate in the named module.
locating the predicate in the named module.
Create a query where name defines the name of the predicate and av the argument vector.
The arity is deduced from av. The predicate is located in the Prolog module user.
This sample shows a query with a compound term as an argument.
the name of the predicate
the argument vector containing the parameters
locating the predicate in the named module.
locating the predicate in the named module.
Provide the next solution to the query. Prolog exceptions are mapped to C# exceptions.
return true if successful and false if there are no (more) solutions.
If the query is closed it will be opened. If the last solution was generated the query will be closed.
If an exception is thrown while parsing (open) the query the _qid is set to zero.
Is thrown if SWI-Prolog Manual PL_next_solution() returns false
Create a of .
If calling ToList() all solutions of the query are generated and stored in the Collection.
A ReadOnlyCollection of PlQueryVariables containing all solutions of the query.
Obtain status information on the Prolog system. The actual argument type depends on the information required.
The parameter queryType describes what information is wanted.
Returning pointers and integers as a long is bad style. The signature of this function should be changed.
PlQuerySwitch
This sample shows how to get SWI-Prologs version number
A PlQuerySwitch.
A int depending on the given queryType
The main purpose of the static PlCall methods is to call a prolog prove or to do some site effects.
Assert.IsTrue(PlQuery.PlCall("is_list", new PlTerm("[a,b,c,d]")));
Assert.IsTrue(PlQuery.PlCall("consult", new PlTerm("some_file_name")));
// or
Assert.IsTrue(PlQuery.PlCall("consult('some_file_name')"));
Create a PlQuery from the arguments, generates the first solution by NextSolution() and destroys the query.
defines the name of the predicate
Is a of arguments for the predicate
Return true or false as the result of NextSolution() or throw an exception.
As but locating the predicate in the named module.
locating the predicate in the named module.
Call a goal once.
Assert.IsTrue(PlQuery.PlCall("is_list([a,b,c,d])"));
Assert.IsTrue(PlQuery.PlCall("consult('some_file_name')"));
The complete goal as a string
NOTE:will be changed in the near future.
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
a goal with *one* variable
the bound variable of the first solution
The List of of this PlQuery.
In the following example you see how the query Variables can be used to set a variable.
Here is a more complex sample where the variables of two queries are connected.
Gets a of the variable names if the query was built by a string.
Provide access to the Argument vector for the query
Enumerate the solutions.
For examples see
Constructors
Enumerate the of one solution.
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
2
Advances the enumerator to the next element of the collection.
true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
The collection was modified after the enumerator was created.
2
Sets the enumerator to its initial position, which is before the first element in the collection.
The collection was modified after the enumerator was created.
2
Gets the element in the collection at the current position of the enumerator.
The element in the collection at the current position of the enumerator.
Gets the current element in the collection.
The current element in the collection.
The enumerator is positioned before the first element of the collection or after the last element.
2
libpl
0 -> Sinput
1 -> Soutput
2 -> Serror
a array of IOSTREAM * pointers
defined in pl-stream.h all with prefix SIO_
A set of function pointers see IOFUNCTIONS in pl-stream.h
a SWI-PROLOG IOSTREAM defined in pl-stream.h
the return value from Snew
the .Net process (Not OS)
The OS and not the .Net process
therefore "Program Files" are either for 64bit or 32bit apps
prolog predicate arity (invokeMethod.IsStatic ? 0 : 1) + ParamArity + (IsVoid ? 0 : 1);
?- closure(v(V1,V2),format('I was called with ~q ~q ...',[V1,V2]).
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
2
Same as Queue except Dequeue function blocks until there is an object to return.
Note: This class does not need to be synchronized
Create new BlockingQueue.
The System.Collections.ICollection to copy elements from
Create new BlockingQueue.
The initial number of elements that the queue can contain
Create new BlockingQueue.
BlockingQueue Destructor (Close queue, resume any waiting thread).
Remove all objects from the Queue.
Remove all objects from the Queue, resume all dequeue threads.
Removes and returns the object at the beginning of the Queue.
Object in queue.
Removes and returns the object at the beginning of the Queue.
time to wait before returning
Object in queue.
Removes and returns the object at the beginning of the Queue.
time to wait before returning (in milliseconds)
Object in queue.
Adds an object to the end of the Queue
Object to put in queue
Open Queue.
Gets flag indicating if queue has been closed.
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
2
These are the namespace comments for SbsSW.SwiPlCs.Exceptions.
The namespace SbsSW.SwiPlCs.Exceptions provides the Exception classes to catch a prolog exception
see SWI-Prolog Manual - 4.9 ISO compliant Exception handling
Prolog exceptions are mapped to C# exceptions using the subclass PlException of
to represent the Prolog exception term.
All type-conversion functions of the interface raise Prolog-compliant exceptions,
providing decent error-handling support at no extra work for the programmer.
For some commonly used exceptions, subclasses of PlException have been created to exploit
both their constructors for easy creation of these exceptions as well as selective trapping in C#.
Currently, these are and .
To throw an exception, create an instance of PlException and use throw() or cppThrow(). The latter refines the C# exception class according to the represented Prolog exception before calling throw().
This exception is thrown if something in the interface went wrong.
This class is the base class to catch exceptions thrown by prolog in C#.
SWI-Prolog Manual - 4.9 ISO compliant Exception handling
To catch a exception thrown by prolog
For a example see .
A PlTerm containing the Prolog exception
The exception is translated into a message as produced by print_message/2. The character data is stored in a ring.
TODO
Used in the PREDICATE() wrapper to pass the exception to Prolog. See PL_raise_exeption().
TODO
see
provide somtimes some additional information about the exceptions reason.
Get the of this exception.
A type error expresses that a term does not satisfy the expected basic Prolog type.
This sample demonstrate how to catch a PlTypeException in C# that is thrown somewhere int the prolog code.
Creates an ISO standard Prolog error term expressing the expected type and actual term that does not satisfy this type.
The type which was expected
The actual term
A domain exception expresses that a term satisfies the basic Prolog type expected, but is unacceptable
to the restricted domain expected by some operation.
For example, the standard Prolog open/3 call expect an IO-Mode (read, write, append, ...).
If an integer is provided, this is a type error, if an atom other than one of the defined IO-modes is provided it is a domain error.
Returns an enumerator that iterates through the collection.
A that can be used to iterate through the collection.
1
Returns an enumerator that iterates through a collection.
An object that can be used to iterate through the collection.
2
Adds an item to the .
The object to add to the .
The is read-only.
Removes all items from the .
The is read-only.
Determines whether the contains a specific value.
true if is found in the ; otherwise, false.
The object to locate in the .
Copies the elements of the to an , starting at a particular index.
The one-dimensional that is the destination of the elements copied from . The must have zero-based indexing.
The zero-based index in at which copying begins.
is null.
is less than 0.
is multidimensional.
-or-
is equal to or greater than the length of .
-or-
The number of elements in the source is greater than the available space from to the end of the destination .
-or-
Type cannot be cast automatically to the type of the destination .
Removes the first occurrence of a specific object from the .
true if was successfully removed from the ; otherwise, false. This method also returns false if is not found in the original .
The object to remove from the .
The is read-only.
Determines whether the contains an element with the specified key.
true if the contains an element with the key; otherwise, false.
The key to locate in the .
is null.
Adds an element with the provided key and value to the .
The object to use as the key of the element to add.
The object to use as the value of the element to add.
is null.
An element with the same key already exists in the .
The is read-only.
Removes the element with the specified key from the .
true if the element is successfully removed; otherwise, false. This method also returns false if was not found in the original .
The key of the element to remove.
is null.
The is read-only.
Gets the value associated with the specified key.
true if the object that implements contains an element with the specified key; otherwise, false.
The key whose value to get.
When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the parameter. This parameter is passed uninitialized.
is null.
Gets the number of elements contained in the .
The number of elements contained in the .
Gets a value indicating whether the is read-only.
true if the is read-only; otherwise, false.
Gets or sets the element with the specified key.
The element with the specified key.
The key of the element to get or set.
is null.
The property is retrieved and is not found.
The property is set and the is read-only.
Gets an containing the keys of the .
An containing the keys of the object that implements .
Gets an containing the values in the .
An containing the values in the object that implements .
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
2
Advances the enumerator to the next element of the collection.
true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
The collection was modified after the enumerator was created.
2
Sets the enumerator to its initial position, which is before the first element in the collection.
The collection was modified after the enumerator was created.
2
Gets the element in the collection at the current position of the enumerator.
The element in the collection at the current position of the enumerator.
Gets the current element in the collection.
The current element in the collection.
The enumerator is positioned before the first element of the collection or after the last element.
2
Copies the elements of the to an , starting at a particular index.
The one-dimensional that is the destination of the elements copied from . The must have zero-based indexing.
The zero-based index in at which copying begins.
is null.
is less than zero.
is multidimensional.
-or-
is equal to or greater than the length of .
-or-
The number of elements in the source is greater than the available space from to the end of the destination .
The type of the source cannot be cast automatically to the type of the destination .
2
Gets an object that can be used to synchronize access to the .
An object that can be used to synchronize access to the .
2
Gets a value indicating whether access to the is synchronized (thread safe).
true if access to the is synchronized (thread safe); otherwise, false.
2
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
2
Advances the enumerator to the next element of the collection.
true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
The collection was modified after the enumerator was created.
2
Sets the enumerator to its initial position, which is before the first element in the collection.
The collection was modified after the enumerator was created.
2
Gets the element in the collection at the current position of the enumerator.
The element in the collection at the current position of the enumerator.
Gets the current element in the collection.
The current element in the collection.
The enumerator is positioned before the first element of the collection or after the last element.
2
Design By Contract Checks.
Each method generates an exception or
a trace assertion statement if the contract is broken.
This example shows how to call the Require method.
public void Test(int x)
{
try
{
Check.Require(x > 1, "x must be > 1");
}
catch (System.Exception ex)
{
PrologCLR.ConsoleTrace(ex.ToString());
}
}
You can direct output to a Trace listener. For example, you could insert
Trace.Cogbot.Clear();
Trace.Cogbot.Add(new TextWriterTraceListener(Console.Out));
or direct output to a file or the Event Log.
(Note: For ASP.NET clients use the Cogbot collection
of the Debug, not the Trace, object and, for a Release build, only exception-handling
is possible.)
Precondition check - should run regardless of preprocessor directives.
Precondition check - should run regardless of preprocessor directives.
Precondition check - should run regardless of preprocessor directives.
Postcondition check.
Postcondition check.
Postcondition check.
Invariant check.
Invariant check.
Invariant check.
Assertion check.
Assertion check.
Assertion check.
Set this if you wish to use Trace Assert statements
instead of exception handling.
(The Check class uses exception handling by default.)
Is exception handling being used?
Exception raised when a contract is broken.
Catch this exception type if you wish to differentiate between
any DesignByContract exception and other runtime exceptions.
Exception raised when a precondition fails.
Precondition Exception.
Precondition Exception.
Precondition Exception.
Exception raised when a postcondition fails.
Postcondition Exception.
Postcondition Exception.
Postcondition Exception.
Exception raised when an invariant fails.
Invariant Exception.
Invariant Exception.
Invariant Exception.
Exception raised when an assertion fails.
Assertion Exception.
Assertion Exception.
Assertion Exception.
The namespace SbsSW.SwiPlCs.Callback provides the delegates to register .NET methods to be
called from SWI-Prolog
It is only possible to call methods
Flags that are responsible for the foreign predicate parameters
0 - PL_FA_NOTHING: no flags.
1 - PL_FA_NOTRACE: Predicate cannot be seen in the tracer.
2 - PL_FA_TRANSPARENT: Predicate is module transparent.
4 - PL_FA_NONDETERMINISTIC: Predicate is non-deterministic. See also PL_retry().
PL_retry()
8 - PL_FA_VARARGS: (Default) Use alternative calling convention. call using t0, ac, ctx
16 - PL_FA_CREF: /* call using t0, ac, ctx */.
/* Internal: ISO core predicate */
PL_EXPORT(void) PL_on_halt(void (*)(int, void *), void *);
typedef void (*PL_abort_hook_t)(void);
See also the example in .
Provide a predefined Delegate to register a C# method to be called from SWI-Prolog
This example is for and shows how o call a C# method with two parameter.
For other samples see the source file CallbackForeigenPredicate.cs in the TestSwiPl VS2008 test project.
true for succeeding otherwise false for fail
With this delegate you can build a call-back predicate with a variable amount of parameters.
The termVector representing the arguments which can be accessed by the
indexer of PlTermV see . The amount of parameters is in
True for succeeding otherwise false for fail
NOT IMPLEMENTED YET
For details to implement see 9.6.17 Registering Foreign Predicates
see also PL_foreign_control
TODO
TODO
TODO
TODO
TODO
See "t_backtrack" in TestSwiPl.CallbackForeigenPredicate.cs
The namespace SbsSW.SwiPlCs.Streams provides the delegates to redirect the read
and write functions of the SWI-Prolog IO Streams.
When is called the *Sinput->functions.read is
replaced by the .NET method 'Sread_function' and *Sinput->functions.write by 'Swrite_funktion'.
For further examples see the methods and
The reason for this is debugging.
The standard SWI-Prolog streams ( input output error )
0 - The standard input stream.
1 - The standard input stream.
1 - The standard error stream.
See
A C stream handle. simple ignore it.
A pointer to a string buffer
The size of the string buffer
A
See
A C stream handle. simple ignore it.
A pointer to a string buffer
The size of the string buffer
A
The online documentation home is here.
This namespace SbsSW.SwiPlCs provides an .NET interface to SWI-Prolog
Overview
Prolog variables are dynamically typed and all information is passed around using the
C-interface type term_t witch is an int. In C#, term_t is embedded in the lightweight struct .
Constructors and operator definitions provide flexible operations and integration with important C#-types (string, int and double).
The list below summarises the important classes / struct defined in the C# interface.
class / structShort description
- A static class represents the prolog engine.
- A struct representing prolog data.
- A vector of .
- A class to query Prolog.
Before going into a detailed description of the CSharp classes let me present a few examples
illustrating the `feel' of the interface. The Assert class in the sample is from the test framework
and has nothing to do with the interface. It shows only which return values are expected.
Creating terms
This very simple example shows the basic creation of a Prolog term and how a Prolog term is converted to C#-data:
PlTerm t1 = new PlTerm("x(A)");
PlTerm t2 = new PlTerm("x(1)");
Assert.IsTrue(t1.Unify(t2));
Assert.AreEqual("x(1)", t1.ToString());
Calling Prolog
This example shows how to make a simple call to prolog.
PlTerm l1 = new PlTerm("[a,b,c,d]");
Assert.IsTrue(PlQuery.PlCall("is_list", l1));
Getting the solutions of a query
This example shows how to obtain all solutions of a prolog query.
takes the name of a predicate and the goal-argument vector as arguments.
From this information it deduces the arity and locates the predicate. the member-function
NextSolution() yields true if there was a solution and false otherwise.
If the goal yielded a Prolog exception it is mapped into a C# exception.
PlQuery q = new PlQuery("member", new PlTermV(new PlTerm("A"), new PlTerm("[a,b,c]")));
while (q.NextSolution())
PrologCLR.ConsoleTrace(s[0].ToString());
There is an other constructor of which simplify the sample above.
PlQuery q = new PlQuery("member(A, [a,b,c])");
foreach (PlTermV s in q.Solutions)
PrologCLR.ConsoleTrace(s[0].ToString());
An other way to get the results is to use to iterate over .
PlQuery q = new PlQuery("member(A, [a,b,c])");
foreach (PlQueryVariables vars in q.SolutionVariables)
PrologCLR.ConsoleTrace(vars["A"].ToString());
It is also possible to get all solutions in a list by .
This could be used to work with LinQ to objects which is really nice. and for further samples.
var results = from n in new PlQuery("member(A, [a,b,c])").ToList() select new {A = n["A"].ToString()};
foreach (var s in results)
PrologCLR.ConsoleTrace(s.A);
Obtain the type of a term, which should be a term returned by one of the other
interface predicates or passed as an argument. The function returns the type of
the Prolog term. The type identifiers are listed below.
see PL_term_type(term_t) in the SWI-Prolog Manual.
In this sample a Prolog variable is created in PlTerm t and the
is checked by his integer representation and his name.
PlTerm t = PlTerm.PlVar();
Assert.AreEqual(1, (int)t.PlType);
Assert.AreEqual(PlType.PlVariable, t.PlType);
0 - PL_UNKNOWN: Undefined
1 - PL_VARIABLE: An unbound variable. The value of term as such is a unique identifier for the variable.
2 - PL_ATOM: A Prolog atom.
3 - PL_INTEGER: A Prolog integer.
4 - PL_FLOAT: A Prolog floating point number.
5 - PL_STRING: A Prolog string.
6 - PL_TERM: A compound term. Note that a list is a compound term ./2.
The PlTerm plays a central role in conversion and operating on Prolog data.
PlTerm implements to support ordering in queries if PlTerm is a List.
Creating a PlTerm can be done by the Constructors or by the following static methods:
PlVar(), PlTail(), PlCompound, PlString(), PlCodeList(), PlCharList() (see remarks)
static methodDescription
- Creates a new initialised term (holding a Prolog variable).
- PlTail is for analysing and constructing lists.
- PlCompound(string)Create compound terms. E.g. by parsing (as read/1) the given text.
- Create a SWI-Prolog string.
- Create a Prolog list of ASCII codes from a 0-terminated C-string.
- Create a Prolog list of one-character atoms from a 0-terminated C-string.
Create a PlTerm but *no* new term_ref it only copies the term_ref into the new object
Used Intern by
- PlException constructor
- PlQueryQ.GetSolutions()
- PlTermV this[int index] indexer
A new PlTerm can be also created by the static methods:
static methodDescription
- Creates a new initialised term (holding a Prolog variable).
- PlTail is for analysing and constructing lists.
- PlCompound(string)Create compound terms. E.g. by parsing (as read/1) the given text.
- Create a SWI-Prolog string.
- Create a Prolog list of ASCII codes from a 0-terminated C-string.
- Create a Prolog list of one-character atoms from a 0-terminated C-string.
Creates a term-references holding a Prolog term representing text.
the text
Creates a term-references holding a Prolog integer representing value.
a integer value
Creates a term-references holding a Prolog float representing value.
a double value
Creates a new initialised term (holding a Prolog variable).
a PlTerm
PlTail is for analysing and constructing lists.
It is called PlTail as enumeration-steps make the term-reference follow the `tail' of the list.
A PlTail is created by making a new term-reference pointing to the same object.
As PlTail is used to enumerate or build a Prolog list, the initial list
term-reference keeps pointing to the head of the list.
The initial PlTerm
A PlTerm for which is_list/1 succeed.
These static methods creates a new compound .
For an example
Create a term by parsing (as read/1) the text.
If the text is not valid Prolog syntax, a syntax error exception is raised.
Otherwise a new term-reference holding the parsed text is created.
The string representing the compound term parsed by read/1.
a new
Create a compound term with the given name from the given vector of arguments. See for details.
The example below creates the Prolog term hello(world).
PlTerm t = PlTerm.PlCompound("hello", new PlTermv("world"));
The functor (name) of the compound term
the arguments as a
a new
Create a compound term with the given name ant the arguments
The functor (name) of the compound term
The first Argument as a
a new
The second Argument as a
The third Argument as a
A SWI-Prolog string represents a byte-string on the global stack.
It's lifetime is the same as for compound terms and other data living on the global stack.
Strings are not only a compound representation of text that is garbage-collected,
but as they can contain 0-bytes, they can be used to contain arbitrary C-data structures.
the string
a new PlTerm
the length of the string
Create a Prolog list of ASCII codes from a 0-terminated C-string.
The text
a new
These static methods creates a new PlCharList TODO TODO .
Create a Prolog list of one-character atoms from a C#-string.
Character lists are compliant to Prolog's atom_chars/2 predicate.
a string
A new PlTerm containing a prolog list of character
Appends element to the list and make the PlTail reference point to the new variable tail.
If A is a variable, and this method is called on it using the argument "gnat",
a list of the form [gnat|B] is created and the PlTail object now points to the new variable B.
This method returns TRUE if the unification succeeded and FALSE otherwise. No exceptions are generated.
The PlTerm to append on the list.
true if successful otherwise false
Appends an element to a list by creating a new one and copy all elements
Note This is a slow version
see my mail from Jan from 2007.11.06 14:44
a closed list
True if Succeed
Appends a list ( PlTail ) to a list by creating a new one and copy all elements
a closed list
True if Succeed
Unifies the term with [] and returns the result of the unification.
return a PlTerm bound to the next element of the list PlTail and advance PlTail.
Returns the element on success or a free PlTerm (Variable) if PlTail represents the empty list.
If PlTail is neither a list nor the empty list, a PlTypeException (type_error) is thrown.
The Next element in the list as a PlTerm which is a variable for the last element or an empty list
Converts to a strongly typed ReadOnlyCollection of PlTerm objects that can be accessed by index
A strongly typed ReadOnlyCollection of PlTerm objects
Converts to a strongly typed Collection of strings that can be accessed by index
A strongly typed string Collection
Returns an enumerator that iterates through the collection.
A System.Collections.Generic.IEnumerator<T that can be used to iterate through the collection.
Returns an enumerator that iterates through a collection.
An System.Collections.IEnumerator object that can be used to iterate through the collection.
Bind termRef to the next element of the list PlTail and advance PlTail.
Returns TRUE on success and FALSE if PlTail represents the empty list.
If PlTail is neither a list nor the empty list, a type_error is thrown.
If PlTerm is a list the string is build by calling ToString() for each element in the list
separated by ',' and put the brackets around '[' ']'.
A string representing the PlTerm.
Convert a PlTerm to a string by write_canonical/1
This Method use and is slow.
return the string of a PlTerm
This methods performs Prolog unification and returns true if successful and false otherwise.
It is equal to the prolog =/2 operator.
See for an example.
This methods are introduced for clear separation between the destructive assignment in C# using =
and prolog unification.
Put a PlTerm with a PlTerm
the second term for unification
true or false
A string to Put with
This methods performs Prolog unification and returns true if successful and false otherwise.
It is equal to the prolog =/2 operator.
See for an example.
This methods are introduced for clear separation between the destructive assignment in C# using =
and prolog unification.
Unify a PlTerm with a PlTerm
the second term for unification
true or false
A string to unify with
Useful e.g. for lists list.Copy().ToList(); list.ToString();
Return a unifies PlTerm.PlVar of this term
Converts the Prolog argument into a string which implies Prolog atoms and strings
are converted to the represented text or throw a PlTypeException.
Converts the Prolog argument using PL_get_chars() using the
flags CVT_ALL|CVT_WRITE|BUF_RING, which implies Prolog atoms and strings
are converted to the represented text or throw a PlTypeException.
If the above call return 0 PL_get_chars is called a second time with the flags CVT_ALL|CVT_WRITE|BUF_RING|REP_UTF8.
All other data is handed to write/1.
A PlTerm that can be converted to a string
A C# string
Throws a PlTypeException exception
Is thrown if the operator is used on an uninitialized PlTerm
Yields a int if the PlTerm is a Prolog integer or float that can be converted
without loss to a int. Throws a PlTypeException exception otherwise
A PlTerm is a Prolog integer or float that can be converted without loss to a int.
A C# int
Throws a PlTypeException exception if
is not a or a .
Is thrown if the operator is used on an uninitialized PlTerm
Yields a long if the PlTerm is a Prolog integer or float that can be converted
without loss to a long. Throws a PlTypeException exception otherwise
A PlTerm is a Prolog integer or float that can be converted without loss to a long.
A C# long
Throws a PlTypeException exception if
is not a or a .
Is thrown if the operator is used on an uninitialized PlTerm
Yields the value as a C# double if PlTerm represents a Prolog integer or float.
Throws a PlTypeException exception otherwise.
A PlTerm represents a Prolog integer or float
A C# double
Throws a PlTypeException exception if
is not a or a .
Is thrown if the operator is used on an uninitialized PlTerm
Compare the instance term1 with term2 and return the result according to the Prolog defined standard order of terms.
Yields TRUE if the PlTerm is an atom or string representing the same text as the argument,
FALSE if the conversion was successful, but the strings are not equal and an
type_error exception if the conversion failed.
a PlTerm
a PlTerm
true or false
test overload
a PlTerm
a int
A bool
Inequality Method overload
a
summary
test
Zero Based
Zero Based
This one should be for checks only e.g.
Check.Require(arg1.TermRefIntern != 0);
If PlTerm is compound and index is between 0 and Arity (including), the nth PlTerm is returned.
If pos is 0 the functor of the term is returned (For a list '.').
See: PL_get_arg/3
To Get the nth PlTerm
a PlTerm
Is thrown if PlTerm is not of Type PlCompound see
Is thrown if (pos < 0 || pos >= Arity)
Is thrown if PL_get_arg returns 0.
Get the of a .
Return true if is a variable
Return true if is a ground term. See also ground/1. This function is cycle-safe.
Return true if is an atom.
Return true if is an atom.
Return true if is an atom.
Return true if is an atom.
Return true if is an atom.
Return true if is a string.
Return true if is an integer.
Return true if is a float.
Return true if is a compound term. Note that a list is a compound term ./2
Return true if is a compound term with functor ./2 or the atom [].
Return true if is a compound term with functor ./2 or the atom [].
Return true if is atomic (not variable or compound).
Return true if is an integer or float.
Return true if is an empty list or nil.
Get the arity of the functor if is a compound term.
and are for compound terms only
Is thrown if the term isn't compound
Get a holding the name of the functor if is a compound term.
The struct PlTermv represents an array of term-references.
This type is used to pass the arguments to a foreign defined predicate (see ),
construct compound terms (see
and to create queries (see ).
The only useful member function is the overloading of [], providing (0-based) access to the elements.
Range checking is performed and raises a ArgumentOutOfRangeException exception.
Create a PlTermV vector from the given PlTerm parameters
Create a new vector with PlTerm as elements
It can be created with elements
or
automatically for 1, 2 or 3 plTerms
Create a vector of PlTerms with elements
The amount of PlTerms in the vector
The second in the vector.
// TODO compare each PlTerm in PlTermV not only the refereces in A0
the first term_t reference of the array
Get the size of a PlTermV
A zero based list
The PlTerm for the given index
Is thrown if (index < 0 || index >= Size)
Is thrown if the operator is used on an uninitialized PlTerm
The class PlFrame provides an interface to discard unused term-references as well as rewinding unifications (data-backtracking).
Reclaiming unused term-references is automatically performed after a call to a C#-defined predicate has finished and
returns control to Prolog. In this scenario PlFrame is rarely of any use.
This class comes into play if the top level program is defined in C# and calls Prolog multiple times.
Setting up arguments to a query requires term-references and using PlFrame is the only way to reclaim them.
see
A typical use for PlFrame is the definition of C# methods that call Prolog and may be called repeatedly from C#.
Consider the definition of assertWord(), adding a fact to word/1:
alternatively you can use
NOTE: in any case you have to destroy any query object used inside a PlFrame
Implement IDisposable.
Do not make this method virtual.
A derived class should not be able to override this method.
Creating an instance of this class marks all term-references created afterwards to be valid only in the scope of this instance.
Reclaims all term-references created after constructing the instance.
Discards all term-references and global-stack data created as well as undoing all unifications after the instance was created.
called by Dispose
This static class represents the prolog engine.
A sample
if (!PlEngine.IsInitialized)
{
String[] empty_param = { "" };
PlEngine.Initialize(empty_param);
// do some funny things ...
PlEngine.PlCleanup();
}
// program ends here
The following sample show how a file is consult via comand-line options.
Dictionary to pin foriegn method delegates so that are not GC'd
Register a C-function to implement a Prolog predicate.
After this call returns successfully a predicate with name (a string) and arity arity (a C# int) is created in module module.
If module is NULL, the predicate is created in the module of the calling context or if no context is present in the module user.
Add a additional namespace by using SbsSW.SwiPlCs.Callback;
For an example see and .
Register a C# callback method
For an example see and .
a delegate to a c# method
true if registration succeed otherwise false
the name of a prolog module Using Modules
The amount of parameters
The name of the method
Initialise SWI-Prolog
The write method of the output stream is redirected to
before Initialize. The read method of the input stream just after Initialize.
A known bug: Initialize work *not* as expected if there are e.g. German umlauts in the parameters
See marshalling in the sorce NativeMethods.cs
For a complete parameter description see the SWI-Prolog reference manual section 2.4 Command-line options.
sample parameter: String[] param = { "-q", "-f", @"some\filename" };
At the first position a parameter "" is added in this method. PL_initialise
For an example see
Try a clean up but it is buggy
search the web for "possible regression from pl-5.4.7 to pl-5.6.27" to see reasons
Use this method only at the last call before run program ends
Stops the PlEngine and the program
SWI-Prolog calls internally pl_cleanup and than exit(0)
To Avoid callbackOnCollectedDelegate MDA
To Avoid callbackOnCollectedDelegate MDA
This is a primitive approach to enter the output from a stream.
Determine which stream to use
A
TODO
Determine which stream to use
A
return : reference count of the engine
If an error occurs, -1 is returned.
If this Prolog is not compiled for multi-threading, -2 is returned.
A reference count of the engine
Returns the integer Prolog identifier of the engine or
-1 if the calling thread has no Prolog engine.
This method is also provided in the single-threaded version of SWI-Prolog, where it returns -2.
Returns TRUE on success and FALSE if the calling thread has no
engine or this Prolog does not support threads.
To test if the prolog engine is up.
Experimental
Stops the PlEngine and the program
SWI-Prolog calls internally exit(0)
This class is experimental
THIS IS ALL @TODO
Creates one constructor for each public constructor in the base class. Each constructor simply
forwards its arguments to the base constructor, and matches the base constructor's signature.
Supports optional values, and custom attributes on constructors and parameters.
Does not support n-ary (variadic) constructors