gpt4 book ai didi

parsing - (Prolog) 将 Lisp s-表达式解析为 Prolog 术语

转载 作者:太空宇宙 更新时间:2023-11-03 18:43:04 25 4
gpt4 key购买 nike

我在 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)}.

最佳答案

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

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

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

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

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

[4]   sequence([]) --> [].

关于parsing - (Prolog) 将 Lisp s-表达式解析为 Prolog 术语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26878906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com