Want to get minimal term_expansion example working

I’m using: SWI-Prolog version 9.3.18 for x64-win64

I want to: write a prolog file that when consulted then it rewrites the term xaxis in the file consulting it or user’s session to the compound term vector(1, 0, 0).

But what I’m getting is: xaxis, no rewriting happening

My code looks like this:
mymoduletest.pro

:- module(mymoduletest, [
	foo/1
	]).

foo(Term) :- writeln(Term).

% code here should translate the atom 
% xaxis into the term vector(1, 0, 0)

user:term_expansion(xaxis, vector(1, 0, 0)).

Then term_expansion_test.pro is

:- ['mymoduletest.pro'].

main :- foo(xaxis).

And then when I run this in the terminal:

PS C:\Users\***> swipl
Welcome to SWI-Prolog (threaded, 64 bits, version 9.3.18)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
Please run ?- license. for legal details.

For online help and background, visit https://www.swi-prolog.org
For built-in help, use ?- help(Topic). or ?- apropos(Word).

1 ?- ['term_expansion_test.pro'].
true.

2 ?- listing(main).
main :-
    foo(xaxis).

true.

3 ?- main.
xaxis
true.

but what I want to happen is something like:

PS C:\Users\***> swipl
Welcome to SWI-Prolog (threaded, 64 bits, version 9.3.18)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
Please run ?- license. for legal details.

For online help and background, visit https://www.swi-prolog.org
For built-in help, use ?- help(Topic). or ?- apropos(Word).

1 ?- ['term_expansion_test.pro'].
true.

2 ?- listing(main).
main :-
    foo(vector(1, 0, 0)). 

true.

3 ?- main.
vector(1, 0, 0)
true.

Thank you for your attention!

If I understood correctly your question, one of the best answers should be the following.

2 Likes

Thanks so much kuniaki! I see now my misunderstanding was in what a “toplevel term” meant. Here foo(xaxis) is a toplevel term where as xaxis is not.

Note that there is also a library(macros) that works anywhere.