Correct way to pass around extra variables in a DCG model?

I’m using: SWI-Prolog version 8.1.9.

I want to pass around one or more extra variables in my (first) DCG attempt. I’m hoping I don’t have to assert everything to the database instead. The variables will contain lists of items that I will use the DCG direct Prolog call feature, the braces feature (e.g. - { some_fact(Fact) } ) to access from various DCG statements.

What is the correct way to do this that will not interact badly with the hidden difference lists a DCG specification maintains? Do I add them to head of the DCG rule? How to do this? If there is a good example/article on this please leave a link.

If I understand correctly, yes, you can add extra arguments to the head of the DCG rule; for example,

some_rule(Fact) -->
    "abcd", { some_fact(Fact) }.

some_fact(F) :- writeln(F).

?- phrase(some_rule(beep), `abcd`).
beep

Then some_rule(Fact) will be expanded to something like some_rule(Fact, In, Out). You can use listing(some_rule//1) to see what exactly it gets expanded into.

And if you want more than a single accumulator, take a look at EDCGs.

2 Likes