tau-prolog icon indicating copy to clipboard operation
tau-prolog copied to clipboard

Feature request: calling Prolog functions from JavaScript

Open jarble opened this issue 4 years ago • 4 comments

Currently, Tau-Prolog requires Prolog queries to be passed as strings to the interpreter:

session.query("nonvar(1)");

But instead of passing a string, I'd prefer to call Prolog functions directly from JavaScript:

var passToProlog = 1;
session.call.nonvar(passToProlog);

I found one possible solution, but it requires a proxy to convert a function call to a query string:

var handler = {
    get: function(target, name) {
        return function(){
          return name+"("+Array.prototype.slice.call(arguments).map(JSON.stringify).join(",")+")";
        };
    }
};
var proxy = new Proxy({}, handler);

var passToProlog = 1;
var query_string = proxy.nonvar(passToProlog); 
console.log(query_string); // output: nonvar(1);

Is it possible to query the interpreter without passing the query as a string?

jarble avatar Nov 23 '19 20:11 jarble

IMO a better interface design would be tagged template literals. That way you can interpolate values and Tau would know how to convert them into internal representations:

let num = someCalculation();
session.query`nonvar(${num})`;

gilbert avatar Feb 01 '20 07:02 gilbert

@jarble using tagged template literals as proposed by @gilbert works for you? Does it address all the use case scenarios?

nicoabie avatar Feb 06 '20 02:02 nicoabie

@nicoabie Tagged template literals might also be useful, though I haven't used them before. Would it be possible to use these literals with JavaScript expressions instead of variables, like this?

session.query`nonvar(${someCalculation()})`;

jarble avatar Feb 06 '20 02:02 jarble

@jarble yeah, you can do that as well! Take a look at the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

nicoabie avatar Feb 06 '20 02:02 nicoabie