I'm new to the language prolog and have been given an assignment regarding parsing in prolog. I need some help in solving the problem.
In the assingment we have the grammar:
Expr ::= + Expr Expr | * Expr Expr | Num | Xer
Xer ::= x | ^ x Num
Num ::= 2 | 3 | .... a Integer (bigger than 1) ...
The token ^
is the same as in math. 5^5
equals 25
.
Parse needs to work both ways: a call with an instantiated list to generate an Ast, while a call with an instantiated Ast should generate similar prefix list.
My assingment says that I need to make a prefix parse that does this:
Example(with the value of Ast removed):
?- parse([+, *, 2, x, ^, x, 5 ], Ast), parse(L, Ast).
X = ...,
L = [+, *, 2, x, ^, x, 5]
I would also like to know how the parse tree will look like.
Prolog has a particular formalism to handle context-free grammars directly: DCGs (Definite Clause Grammars). Your example translates almost immediately into a DCG:
Now, you already can test sentences:
You can even generate all possible sentences like so:
And, finally, you can add the abstract syntax tree to your definition.
So now you can use it as desired:
Just a nitpick: The interface predicate to DCGs is
phrase/2
notparse/2
.