 numbervars(+Term, 
+Start, -End)
numbervars(+Term, 
+Start, -End)$VAR(N), 
where N is the number of the variable. Counting starts at
Start. End is unified with the number that should 
be given to the next variable.bugOnly tagged 
integers are supported (see the Prolog flag max_tagged_integer). 
This suffices to count all variables that can appear in the largest term 
that can be represented, but does not support arbitrary large integer 
values for Start. On overflow, a representation_error(tagged_integer) 
exception is raised. The example below illustrates this. 
Note that the toplevel prints '$VAR'(0) as A due 
to the
numbervars(true) option used to print answers.
?- Term = f(X,Y,X),
   numbervars(Term, 0, End, [singleton(true)]),
   write_canonical(Term), nl.
f('$VAR'(0),'$VAR'('_'),'$VAR'(0))
Term = f(A, _, A),
X = A,
Y = B,
End = 2.
See also the numbervars option to write_term/3 
and numbervars/4.