4

我在 Prolog 中编写了一个解析器,它接受一个标记化列表,并且应该返回一个表达式,其中变量与评估方程的值统一:

Tokens = ['(', is, v('X',3),'(', +, 1, 2, ')', ')' ]
Expr = (3 is 1 + 2)

目前,我的解析器正在返回以下内容:

Expr [is, _G32432, '(', +, 1, 2, ')'|_G19343]

有谁知道我如何修复这个解析器?我已包含以下代码:

%Definite Clause Grammar (DCG) for Lisp s-expressions
expression(N) --> atom(N).
expression(N) --> integer(N).
expression(N) --> variable(N).
expression(N) --> list(N).
list(N) --> ['('], sequence(N), [')'].
sequence(_) --> [].
sequence([H|T]) --> expression(H), sequence(T).
%atom(_) --> [].
atom(N) --> [N],{atom(N)}.
%variable(_) --> [].
variable(N) --> [v(_,N)],{var(N)}.
%integer(_) --> [].
integer(N) --> [N],{integer(N)}.    

evaluate(String, Expr):-
tokenize(String, Tokens),
expression(Expr,Tokens,[]),
write('Expression: '), write_term(Expr, [ignore_ops(true)]).

编辑:下面是我的解析器工作版本:

expression(N) --> atom(N).    %an atom is a type of expression
expression(N) --> integer(N). %an integer is a type of expression
expression(N) --> variable(N). %a variable is a type of expression
expression(M) --> list(N),{M=..N}.  
list(N) --> ['('], sequence(N), [')'].   %a sequence within parens is a type of list
sequence([]) --> [].                 %a sequence can be empty
sequence([H|T]) --> expression(H), sequence(T).  %a sequence can be composed of an expression
% sequence([]) --> []. %and a sequence atom(_) --> [].
atom(N) --> [N],{atom(N),N \= '(', N \= ')'}. %parens are not atoms, but all other Prolog atoms 
% If N is a variable and it is within the v(Label,X) data structure,
% then it is a var in this grammar
variable(N) --> [v(_,N)],{var(N)}.
%variable(_) --> [].
%integer(_) --> [].
integer(N) --> [N],{integer(N)}.
4

1 回答 1

3

您的输入标记之一是 [1]。请注意,它永远不会匹配您的规则 [2],因为N它是整数而不是变量(也是'X'原子而不是变量)。

[1]   v('X',3)
[2]   variable(N) --> [v(_,N)],{var(N)}.

将 [2] 更改为 [3] 可解决此问题。

[3]   variable(N) --> [N], {var(N)}.

PS:还要确保sequence//1通过用 [4] 替换相应的行来关闭基本情况下的结果表达式。

[4]   sequence([]) --> [].
于 2014-11-12T06:14:30.997 回答