Tau Prolog - how to convert a prolog list into a JavaScript array

312 views Asked by At

I want to use Tau Prolog together with JavaScript on a Node Server, following this tutorial, which works well. I need to convert the answers in a JavaScript compatible format, especially lists to arrays, or objects and vice versa.

I changed the Prolog program and goal in a way that it returns a list

Program: test(t, [64,65,100,120]).

Goal: test(t, X).

which returns with

console.log(session.format_answer(answer));

X = [64,65,100,120]

too the console. How can I get only the list and assign it to a js variable?

I tried

answer.lookup("X")

which gives me

Term {
ref: 1258,
id: '.',
args: [
Num { is_float: false, value: 64 },
Term { ref: 1257, id: '.', args: [Array], indicator: './2' }
],
indicator: './2'
}

Which is not very comfortable to access. The args array seems to be the list. I managed to get single list elements with

console.log(answer.links.X.args[1].args[1].args);

to get the third list element.
What is the best way to use complex answers and lists in JavaScript?

1

There are 1 answers

0
José Antonio Riaza Valverde On BEST ANSWER

Just for completeness, I replicate this answer here.

You can write a function to transform Prolog lists to arrays:

function fromList(xs) {
    var arr = [];
    while(pl.type.is_term(xs) && xs.indicator === "./2") {
        arr.push(xs.args[0]);
        xs = xs.args[1];
    }
    if(pl.type.is_term(xs) && xs.indicator === "[]/0")
        return arr;
    return null;
}

Example:

var session = pl.create();
session.query("X = [1,2,3].");
session.answer(a => console.log(fromList(a.lookup("X")))); // [ {...}, {...}, {...} ]

Note that elements in array are still Tau Prolog objects.