Tau-Prolog is an implementation of Prolog in pure Javascript.
Here is a basic example :
// Create a Prolog session
let program = `
parent(john, mary).
parent(susan, mary).
parent(mary, alice).
parent(mary, bob).
parent(paul, bob).
grandparent(X, Y) :- parent(X, Z), parent(Z, Y).
sibling(X, Y) :- parent(Z, X), parent(Z, Y), X \\= Y.
ancestor(X, Y) :- parent(X, Y).
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).
`;
function showAnswer(answer, context) {
if (pl.type.is_substitution(answer)) {
for (let key in answer.links) {
document.write(answer.links[key].id + "<br>"); // Extract only the name
}
} else {
console.log("no answer");
}
}
class PrologSession {
constructor() {
this.session = pl.create(1000);
this.consultationDone = false;
this.consultationResolve = null;
// Load Prolog program
this.session.consult(program, {
success: () => {
this.consultationDone = true;
if (this.consultationResolve) {
this.consultationResolve(); // ✅ Resolves any pending queries
this.consultationResolve = null; // Prevents multiple calls
}
},
error: (err) => {
console.error("Prolog consultation error:", err);
}
});
}
waitForConsultation() {
return new Promise((resolve) => {
if (this.consultationDone) {
resolve(); // If already done, resolve immediately
} else {
this.consultationResolve = resolve; // Store resolve function
}
});
}
query(queryString, context) {
document.write(context + "<br />");
this.waitForConsultation().then(() => {
this.session.query(queryString, {
success: () => {
this.session.answers((a) => showAnswer(a, context));
},
error: (err) => {
console.error("Query error:", err);
}
});
});
}
}
// Example usage
const prolog = new PrologSession();
prolog.query("ancestor(X, bob).", "Ancestors of Bob are: ");
Top comments (0)