DEV Community

artydev
artydev

Posted on • Edited on

Tau-Prolog : enhancing sample

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: ");

Enter fullscreen mode Exit fullscreen mode

Demo

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay