1
votes

I'm writing a code generator that converts definite clause grammars to other grammar notations. To do this, I need to expand a grammar rule:

:- initialization(main).

main :- 
        -->(example,A),writeln(A).
% this should print ([a],example1), but this is a runtime error

example --> [a],example1.
example1 --> [b].

But -->(example, A) doesn't expand the rule, even though -->/2 appears to be defined here. Is there another way to access the definitions of DCG grammar rules?

2
@GuyCoder listing(example) doesn't print [a],example1. It prints example(A, A). example([a|A], B) :- example(A, B) instead. - Anderson Green
Why do you want this? You are interfering with built/in mechanisms. Why not use another operator? - false
@false I have already written several DCG grammars, so I want to convert them to CHR grammars without manually re-writing them. - Anderson Green
Better transform that file in one fell swoop. - false

2 Answers

1
votes

This is a guess of what your are expecting and why you are having a problem. It just bugs me because I know you are smart and should be able to connect the dots from the comments. (Comments were deleted when this was posted, but the OP did see them.)

This is very specific to SWI-Prolog.

When Prolog code is loaded it automatically goes through term expansion as noted in expand.pl.

Any clause with --> will get expanded based on the rules of dcg_translate_rule/2. So when you use listing/1 on the code after it is loaded, the clauses with --> have already been expanded. So AFAIK you can not see ([a],example1) which is the code before loading then term expansion, but example([a|A], B) :- example(A, B) which is the code after loading and term expansion.

The only way to get the code as you want would be to turn off the term expansion during loading, but then the code that should have been expanded will not and the code will not run.

You could also try and find the source for the loaded code but I also think that is not what you want to do.

Based on this I'm writing a code generator that converts definite clause grammars to other grammar notations. perhaps you need to replace the code for dcg_translate_rule/2 or some how intercept the code on loading and before the term expansion.

HTH


As for the error related to -->(example,A),writeln(A). that is because that is not a valid DCG clause.

1
votes

As you wrote on the comments, if you want to convert DCGs into CHRs, you need to apply the conversion before the default expansion of DCGs into clauses. For example, assuming your code is saved to a grammars.pl file:

?- assertz(term_expansion((H --> B), '--->'(H,B))).
true.

?- assertz(goal_expansion((H --> B), '--->'(H,B))).
true.

?- [grammars].
[a],example1
true.