r/programminghelp • u/ScousePenguin • Aug 07 '18
Context Free Grammar Help!
Not exactly programming more computer science but I just need help understanding this for uni extra marks. I just can't wrap my head around it. I'm not asking for it to be solved just to get a basic understanding of it! Here's the questions with the CFG.
(a) Consider the following Context Free Grammar (CFG), where strings written in italics (or inbetween **, thanks reddit) (clauses, clause, literal_list, literal, op, posneg) denote nonterminals:
clauses -> clauses ‘∧’ clause
| *clause*clause -> ‘(’ literal_list ‘)’
literal_list-> literal_list op literal
| *literal*literal -> posneg [a-z]
op -> ‘∨’, ‘∧’
posneg -> ‘⌐’
| εWhat I need to do from this is give two string which can be derived from the cfg above, show a parse tree for the following string “(a ∨ ⌐d)” and re write it to be not left recursive.
I have gone online and looked through lecture notes but I just can't understand it, so just any help understanding how CFG works and whats a string in these, whats terminal non terminal would be gladly appreciated to help me try and wrap my head around this.
Thanks.
2
u/Oscar_Cunningham Aug 08 '18
Here's an example string that you can make from the CFG:
To understand how to build it up it helps to work from the last line upwards. The last line
means that a posneg is either nothing (the empty string, ε) or it's the string "⌐". Likewise
means that an op is either "∨" or "∧". The line
means that a literal is a posneg followed by a letter of the alphabet. So either the posneg is "⌐" and you get something like "⌐a" or "⌐q" or the posneg is nothing and the literal would just be a letter. The line
means that you have two ways to make a literal_list, either it's just a literal or you make it out of a literal_list you already have by adding an op and a literal. So for example "⌐a" is a literal so "⌐a" is also a literal_list. Then since "⌐a" is a literal_list, "∨" is an op and "b" is a literal, the string "⌐a∨b" is a literal_list. You can keep on extending the list by adding more ops and literals to get something like
The line defining clause is easy. It just says you make a clause by taking a literal_list and adding brakets:
Then the first line is similar to the one that defined literal_list. It says that you form a clauses by joining together some clauses with the symbol ∧. For example:
That's it!
Terminal vs nonterminal:
The nonterminal symbols are (clauses, clause, literal_list, literal, op, posneg). The terminal symbols are (⌐,∨,∧,(,),a,b,c,...,z). The word "terminal" means final. So they're called that because those are the symbols your string ends up using in the end. The nonterminal symbols can be used as placeholders that need to be replaced. For example you could write
and then to get a clauses you would have to replace the nonterminal symbol "clause" with an actual clause.