SWI-Prolog -- term_variables/2

Did you know ... Search Documentation:
SWI-Prolog owl logo Predicate term_variables/2
Availability:built-in
[ISO]term_variables(+Term, -List)
Unify List with a list of variables, each sharing with a unique variable of Term.117This predicate used to be called free_variables/2 . The name term_variables/2 is more widely used. The old predicate is still available from the library library(backcomp). The variables in List are ordered in order of appearance traversing Term depth-first and left-to-right. See also term_variables/3 and nonground/2. For example:
?- term_variables(a(X, b(Y, X), Z), L).
L = [X, Y, Z].
Tags are associated to your profile if you are logged in
Tags:
LogicalCaptain said (2021年05月19日T13:22:42):0 upvotes 0 0 downvotes
Picture of user LogicalCaptain.

Of course, we are talking about term as it is at call time, not as it syntactically appears in the code :

For example. the same query as in the example, but Y is no longer an unbound variable. It thus does not appear in the result:

?-
Y=foo(Z),
term_variables(a(X, b(Y, X), Z), L).
Y = foo(Z),
L = [X,Z].

Below, Y is bound to foo(A), becoming bound but introducing another unbound variable:

?-
Y=foo(A),term_variables(a(X, b(Y, X), Z), L).
Y = foo(A),
L = [X,A,Z].

Using the anonymous variable gives exactly what is expected:

?-
term_variables(a(_, b(_, _), _), L).
L = [_12464,_12458,_12460,_12468].

If a variable becomes bound later, the answer will reflect that:

?-
term_variables(a(X, b(Y, X), Z), L),X=1.
X = 1,
L = [1,Y,Z].

This can be used to collect the bindings for an unknown goal (in case you have to do that, but if your goal is unknown ... how are you going to interprete the bindings?)

?-
Goal=member(X-Y,[1-2,3-4,5-6]),
term_variables(Goal,Vars),
findall(Vars,Goal,Bag).
Goal = member(X-Y,[1-2,3-4,5-6]),
Vars = [X,Y],
Bag = [[1,2],[3,4],[5,6]].
?-
Goal=member(X-4,[1-A,3-4,5-B]),
term_variables(Goal,Vars),
bagof(Vars,Goal,Bag).
Goal = member(X-4,[1-A,3-4,5-B]),
Vars = [X,A,B],
Bag = [[1,4,_6574],[3,_6544,_6550],[5,_6520,4]].
login to add a new annotation post.

AltStyle によって変換されたページ (->オリジナル) /