FrankTan
FrankTan

Reputation: 1686

prolog term to string

i have a prolog list like this:

[p(X,Y,Z),r(H,G,K)] 

and i want convert it into this:

'p(X,Y,Z)r(H,G,K)'  

it is just a list of predicate, that should be transformed into a string.

Do you have any idea? ( I use prolog)

Upvotes: 2

Views: 3306

Answers (2)

Kaarel
Kaarel

Reputation: 10672

You can read terms using the variable_names option, which gives you a list of Name=Variable pairs in the read term. So maybe this is what you need.

Here is a command line that reads the term, then unifies the variables with their names and finally prints the result into an atom in the way that you specified in your question.

?- read_term(Term, [variable_names(VarNames)]), maplist(call, VarNames),
                                with_output_to(atom(Atom), maplist(write, Term)).
|: [p(X,Y,Z),r(H,G,K)].
Term = [p('X', 'Y', 'Z'), r('H', 'G', 'K')],
VarNames = ['X'='X', 'Y'='Y', 'Z'='Z', 'H'='H', 'G'='G', 'K'='K'],
Atom = 'p(X,Y,Z)r(H,G,K)'.

Note that it modifies the read term, so you might want to make a copy of it first (copy_term/2).

Upvotes: 1

svick
svick

Reputation: 244767

I think doing that is not possible. After you declare a variable, its name is lost for further processing.

EDIT:

Something like this is possible, if you don't mind losing the names. At least in SWI-Prolog:

?- format(atom(A), "~w~w", [p(X,Y,Z),r(H,G,K)]).
A = 'p(_G924,_G925,_G926)r(_G931,_G932,_G933)'.

Upvotes: 3

Related Questions