'Whats the equivalent of atom_to_term/3 across Prolog systems?
I find that SWI-Prolog offers:
atom_to_term(+Atom, -Term, -Bindings)
Use Atom as input to read_term/2 using the option variable_names
and return the read term in Term and the variable bindings in Bindings.
https://www.swi-prolog.org/pldoc/man?predicate=atom_to_term/3
But I am having a hard time, figuring out what other Prolog systems offer in this respect . Maybe some people did already obtain solutions, that they might want to share?
Example what it does:
?- atom_to_term('X + Y', T, N).
T = _A+_B,
N = ['X'=_A, 'Y'=_B].
Solution 1:[1]
Both SWI and ECLiPSe support term_string/3 and atom_string/2, with which you can write
atom_to_term(A, T, N) :-
atom_string(A, S),
term_string(T, S, [variable_names(N)]).
To make it quietly fail for malformed strings (syntax errors), use
atom_to_term(A, T, N) :-
atom_string(A, S),
term_string(T, S, [variable_names(N), syntax_errors(quiet)]).
Other error handling options are fail (print syntax error message and fail) and error (throw error/2 term).
Solution 2:[2]
Logtalk, which runs on all those backend Prolog systems and several more, provides a portable term_io library that implements reading/writing terms from/to atoms, chars (lists of characters), and codes (lists of character codes). For example using GNU Prolog:
$ gplgt
...
| ?- {term_io(loader)}.
...
% (0 warnings)
(202 ms) yes
| ?- term_io::read_term_from_atom('X + Y', Term, [variable_names(Vars)]).
Term = A+B
Vars = ['X'=A,'Y'=B]
yes
A period at the end of the atom is optional:
| ?- term_io::read_term_from_atom('a(X, Y).', Term, [variable_names(Vars)]).
Term = a(A,B)
Vars = ['X'=A,'Y'=B]
(1 ms) yes
Solution 3:[3]
Ok, I already found for GNU Prolog, that this could work:
atom_to_term(A, T, N) :-
atom_concat(A, ' .', B),
read_term_from_atom(B, T, [variable_names(N)]).
The example passes:
?- atom_to_term('X + Y', T, N).
N = ['X'=A,'Y'=B]
T = A+B
But what about Tau Prolog (Browser), Scryer Prolog, SICStus Prolog, ECLiPSe Prolog etc..?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 |
