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 つは [1] です。Nは整数であり、変数ではないため (また、'X'アトムであり、変数ではない) 、ルール [2] と一致しないことに注意してください。

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

[2] を [3] に変更すると、この問題は解決します。

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

sequence//1PS: また、対応する行を [4] に置き換えて、基本ケースの結果の式を必ず閉じてください。

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