# Prolog – 解析

```Expr ::= + Expr Expr | * Expr Expr | Num | Xer
Xer  ::= x | ^ x Num
Num  ::= 2 | 3 | .... a Integer (bigger than 1) ...```

```?- parse([+, *, 2, x, ^, x, 5 ], Ast), parse(L, Ast).
X = ...,
L = [+, *, 2, x, ^, x, 5]```

Prolog有一种特殊的形式主义来直接处理无上下文语法：DCG(Definite Clause Grammars).您的示例几乎立即转换为DCG：

```expr --> [+], expr, expr | [*], expr, expr | num | xer.

xer --> [x] | [^], [x], num.

num --> [2] | [3] | [4] | [5].```

```?- phrase(expr, [+, *, 2, x, ^, x, 5 ]).
true ;
false.

?- phrase(expr, [+, *, *, 2, x, ^, x, 5 ]).
false.```

```?- length(L, N), phrase(expr, L).
L = [2],
N = 1 ;
L = [3],
N = 1 ;
...```

```expr(plus(A,B)) --> [+], expr(A), expr(B).
expr(mul(A,B)) --> [*], expr(A), expr(B).
expr(Num) --> num(Num).
expr(Xer) --> xer(Xer).

xer(var(x)) --> [x].
xer(pow(var(x),N)) --> [^], [x], num(N).

num(num(2)) --> [2].
num(num(3)) --> [3].
num(num(4)) --> [4].
num(num(5)) --> [5].```

```?- phrase(expr(AST), [+, *, 2, x, ^, x, 5 ]), phrase(expr(AST),L).
AST = plus(mul(num(2), var(x)), pow(var(x), num(5))),
L = [+, *, 2, x, ^, x, 5] ;
false.```