Consulting an atom

88 views Asked by At

One can easily consult a Prolog file using consult/1 or [filename]..

Suppose I generate Prolog code as an atom. I can in a predicate write that code to a file and then consult it, and query a predicate from that code, e.g.

example :-
    generate_stuff(X),
    write_to_file(X,'filename.pl'),
    consult('filename.pl'),
    predicate_in_filename.

How would I go about doing the same thing but without writing X (the code) to a file? I'm having no luck with assert which takes a term as input whereas here I have complete code in an atom.

2

There are 2 answers

3
mat On BEST ANSWER

The clean way is of course to not even produce an atom in the first place, but a more structured representation from the start.

However, if you really want to use atoms and later treat them as structured terms, use atom_to_term/3, then assert the clause.

For example:

?- atom_to_term('p(X, Y) :- dif(X, Y)', T, Vs).
T =  (p(_G925, _G926):-dif(_G925, _G926)),
Vs = ['X'=_G925, 'Y'=_G926].

In your case, you can simply ignore Vs:

?- atom_to_term('p(X, Y) :- dif(X, Y)', T, _).
T =  (p(_G916, _G917):-dif(_G916, _G917)).
1
Fatalize On

For posterity, here is how I did it, provided that you have only one term in each atom of the list:

%...
maplist(read_term_from_atom_, ListOfAtoms, ListOfTerms),
maplist(asserta, ListOfTerms),
%...

read_term_from_atom_(A, B) :-
    read_term_from_atom(A, B, []).