Is there a way to configure YAP (and/or SWI prolog) so they will preserve variable names in any call to term_to_atom/2
?.
For example, when I execute this:
term_to_atom(member(X, [1,2]), A).
I obtain this answer:
A = 'member(_131405,[1,2])'
Where X
has been replaced by its internal representation.
However, I would like to get this answer instead:
A = 'member(X,[1,2])'
Thanks for any help!
There are two issues involved. How to get the variable name
X
into the system, and how to get a term with such a variable into the atom.The
X
you type in is read by the top level which converts it to a regular variable which does not have a name associated. Let's see that in YAP:The
|:
is YAP's prompt for input. And we have enteredX+3*Y+X.
However, the variableTerm
contains_A
and_B
(names chosen by the top level) in place ofX
andY
. So the information is lost and cannot be restored once it is read by read/1.You have to access that information differently with the more general built-in for reading
read_term/2,3
and the optionvariable_names/1
.So the read option
variable_names/1
gives you the information to restore the variable names. For each named variable read byread_term/2
there is a structureName = Variable
where Name is an atom representing the variable name. Above,'X'
is the name capital X.Anonymous variables, that is variables whose name is
_
, do not occur in the list of variable names. They can be rapidly extracted like so:So much for the reading.
Now for the writing. We cannot write the term directly but have to accompany it with the list
Eqs
. Let's call the new predicateterm_to_atom(Term, Eqs, Atom)
. In both YAP and SWI there iswith_output_to(Output, Goal)
which writes the output ofGoal
to different destinations likeatom(A)
. So you can now use write_term/2 to write the term as you please. An example:The variable _131284 looks very ugly. To get variables associated with their names for printing we can implement
term_to_atom/3
as follows:And use it like so:
variable_names/1
exists as a write option in ISO, Minerva, Jekejeke, GNU, B, SWI, YAP, and SICStus.In SICStus, the originator of writing terms to lists, one writes:
The following was an ISO incompatible work around for YAP prior to 6.3.4. It is no longer necessary. As for the differences to a separate write option:
term_to_atom/3
as defined below interferes with constraints and does not correctly render'$VAR'/1
.