Print a term with variables as letters, not numbers

I want to print a term with variable letters like this:

?- print_term(f(X,Y,X), []).
f(A,_,A)

I want to do the similar thing with format/2 or 3 and I cannot find correct options for it.

?- format('~W', [f(X,Y,X), [numbervars(false)]]).
f(_12036,_12038,_12036)
?- format('~W', [f(X,Y,X), [numbervars(true)]]).
f(_12036,_12038,_12036)
?- format('~W', [f(X,Y,X), []]).
f(_12036,_12038,_12036)

I am using swipl 8.0.3

Use this. Note that the numbersvars(true) option of the write family just tell these predicates to interpret '$VAR'(N) as A, B, … You have to number the variables yourself. Note that if you need to print multiple terms with possible sharing variables you should numbervars them together, for example by passing a list to numbervars/4.

Finally, the double negation is to make sure that the bindings are undone before proceeding and thus the term is not modified by the operation.

    \+ \+ ( numbervars(Term, 0, _, [singletons(true)]),
            format('~W', [Term, [numbervars(true)]])
          )
2 Likes

Thank you for your help and explanation.

A note, format uses numbervars(true) option by default. So only format('~w', [Term]) also works with numbervars.
singletons(true) I like this option to reveal singleton vars.