C# API
The CSProlog.Core package has the engine and the term types. All public types are in the CSProlog namespace.
Terms
A Prolog term is one of five C# types, which all derive from Term. Terms never change after they are made.
| Type | Example | Prolog |
|---|---|---|
Atom |
new Atom("socrates") |
socrates |
Var |
new Var("X") |
X |
Integer |
new Integer(42) |
42 |
Float |
new Float(1.5) |
1.5 |
Compound |
new Compound("human", new Atom("socrates")) |
human(socrates) |
- An atom can have any name, such as
new Atom("Hello World"). - A variable name must start with an uppercase letter or an underscore.
- Two
Varobjects are different variables, even if they have the same name. Keep the object in a C# variable to use it again. Integerholds aBigInteger, so it can be of any size.Floatholds adouble. It cannot be infinity or NaN, sonew Float(double.NaN)throwsArgumentOutOfRangeException.- A number in a solution can be an
Integeror aFloat. For example,X is 4 / 2gives theFloat2.0, not theInteger2, so check the type with a pattern such assolution[x] is Float { Value: var value }. - A compound term needs at least one argument.
Term.CreateList builds a Prolog list.
var list = Term.CreateList(new Atom("a"), new Atom("b")); // [a, b]
var empty = Term.CreateList(); // []A list is a chain of compound terms named '.', as in ISO Prolog, and the empty list is the atom [].
Adding clauses
AddClause adds a fact, or a rule written as the compound term :-(Head, Body).
var engine = new PrologEngine();
var x = new Var("X");
engine.AddClause(new Compound("human", new Atom("socrates")));
engine.AddClause(new Compound(":-", new Compound("mortal", x), new Compound("human", x)));Running queries
Solve runs a query and returns IEnumerable<Solution>. A solution reads the value of a variable by the Var object.
var who = new Var("Who");
foreach (var solution in engine.Solve(new Compound("mortal", who)))
{
Console.WriteLine(solution[who]); // socrates
}- Each step of the
foreachloop backtracks into the query and finds the next solution. - To get only the first solution, use
FirstOrDefault(). To check whether there is a solution, useAny(). - A variable that has no value gives a
Var.
Errors
A Prolog error comes out of Solve as a PrologException. Its ErrorTerm holds the error term, such as error(existence_error(procedure, foo/0), _). Prolog code can catch the same error with catch/3.
try
{
engine.Solve(new Atom("foo")).ToList();
}
catch (PrologException exception)
{
Console.WriteLine(exception.ErrorTerm);
}Cancelling a query
Solve takes a CancellationToken. When the token is cancelled, the next step of the enumeration throws OperationCanceledException.
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5));
foreach (var solution in engine.Solve(query, cancellation.Token))
{
// ...
}Running queries without blocking the UI
SolveAsync returns IAsyncEnumerable<Solution>. It runs the query for a short time, then gives control back to the caller, again and again. On a single thread, as in Blazor WebAssembly, the UI keeps working during a long query, and a stop button can cancel it.
await foreach (var solution in engine.SolveAsync(query, cancellationToken))
{
// ...
}The occurs check
By default, unification has no occurs check, as in most Prolog systems. So X = f(X) makes a cyclic term. Turn on the occurs check to prevent cyclic terms. It costs some speed.
var engine = new PrologEngine { OccursCheck = true };Prolog code can also change it with set_prolog_flag(occurs_check, true). A change takes effect right away, even in a running query.
Tracing
Set Tracer to see each step of a query. The engine calls it at each port of a traced call. The ports are Call, Exit, Redo, and Fail. The returned TraceAction tells the engine what to do next.
engine.Tracer = e =>
{
Console.WriteLine($"{e.Port}: ({e.Depth}) {engine.FormatTerm(e.Goal)}");
return ValueTask.FromResult(TraceAction.Continue);
};
engine.Solve("trace, member(X, [a, b]).").ToList();TraceAction |
What the engine does |
|---|---|
Continue |
Goes on. |
Skip |
Hides the steps inside this call, until it exits or fails. |
Leap |
Turns off the trace mode, and goes on until a spy point. |
Abort |
Stops the query. It throws OperationCanceledException. |
Calls are traced after trace/0, until notrace/0. A predicate with a spy point (spy/1) is always traced. Control constructs such as ,/2 and !/0 are not traced.
The tracer can wait, for example for a button. Use SolveAsync then. Solve blocks the thread until the tracer answers.