Frage

I have the DCG format I want to simulate this code:

 s --> [a].
 s --> s, s.

and invokes with:

 ?- phrase(s, X).

I made up with the below code, but something is missing.

rule(s,[a]).
rule(s,[s,s]).

And for the phrase part I don't know how can call these rule such as in phrase?

War es hilfreich?

Lösung

a DCG is usually implemented adding a pair of arguments to the rules, to get the fast list processing required to accomplish the parsing, an application of a basic technique known as difference lists. You can inspect the translation with listing/1:

?- [user].
|: s --> [a].
|: s --> s, s.
% user://1 compiled 0.04 sec, 4 clauses

?- listing(s).
s([a|A], A).
s(A, C) :-
    s(A, B),
    s(B, C).

phrase/2 'just' associates the tokens' list to the first grammar (hidden) argument, and associates the empty list to the second hidden one, to means that the entire tokens' list must be consumed by parsing.

Since you are simulating the DCG, your task then should reduce to adding a token list to your code. If the code is properly implemented (not easy to do right), the simulation will be able to parse as well as generate any legal phrase. In your case, a sequence of at least 1 a.

Without knowing how you interpret your rule/2, it's hard to give any sensible hint...

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top