I have a simple grammar such as
S::=a S b
S::=[] (empty string)
Now i want to write a parser for the above grammar like
cfg('S', [a,'S',b])
which generates a sentence aaabbb by left most derivation.
I’m not good enough to handle dcg/cfg in prolog.
So pls help me with this example so that i can go ahead and try something bigger.
Consider this DCG code:
to run a predicate you defined by DCG you should add two more arguments at the end: the “input” and what it’s left. If you want to recognize the whole list you simply put []. So, when you run it you get:
If you wanted some sort of “return” string you could add it as an extra arg. To write prolog code in a dcg clause you use {}:
and you get:
we generated all the strings that are recognized by this grammar; usually you just want to check if a string is recognized by the grammar. to do that you simply put it as input:
note that we put the S::=[] rule first otherwise prolog would fall in a infinite loop if you asked to generate all the solutions. This problem might not be trivial to solve in more complex grammars. To get the solutions you can use length/2:
even if your code is: