Term rewriting / expansion...tutorials, other references?

Hi, I am almost done with the basics of my AST, I have implemented the general recurisiveness of the source orm and three of the 84 reserved words!

I am wondering of term_expansion/2 et al. can be of some assistance in cutting down the boiler plate, making things easier to read and reason about.

My basic n00b question is this: what is the advantage of using term_expansion of just calling a subroutine predicate apart from the simple fact that term_expansion is compile time and subroutines are run time.

Is that the only benefit really?

I have read all of the posts on this forum, created some simple expansions of my own with debug statements and mostly it works but sometimes I get odd errors:


term_expansion(X, Out) :-
    (   functor(X, foo, 2)
    %
    % it's a foo, let's muck about with it
    %
    ->  debug(eric, 'fiddle: ~p~n',[X]),
        Out = (
            foo(X,Y) :-
                Y is X+1,
                format('adding ~p and 1 is ~p',[X,Y])
        )

    %% Leave it alone
    ;   Out = X
    ).

foo(_X,_Y).

foo(_Z).

% ?- foo(10,Out).
% ?- listing(foo).
% ?- debug(eric).

at the emacs prolog session I get this message:

|    % fiddle: foo(_6044,_6046)

ERROR: /tmp/prolcomp6531Hph.pl:28:
	Arithmetic: `foo(_6568,_6590)' is not a function
true.
?- 

I can see my debug statement but right now I am floundering due to a complete lack of knowledge! I made the vars anonymous because otherwise it was complaining about singleton variables.

Thanks,
Sean.

1 Like

You’re using the variable X for both the term to be expanded and the first argument of foo/2. Simply use different variables.

:man_facepalming: …yes…painfully clear now! :expressionless: