gpt4 book ai didi

string - 从 Prolog 中的字符串中删除空格

转载 作者:行者123 更新时间:2023-12-01 15:43:29 26 4
gpt4 key购买 nike

我在 Prolog 中编写了解析器。我还没说完。它是代码的一部分。下一步是消除字符串中的所有空格。

parse(Source, Tree) :-  kill_whitespace(Source, CleanInput), % remove whitespaces
actual_parse(CleanInput, Tree).

actual_parse(CleanInput, Tree):- phrase(expr(Tree),CleanInput).

expr(Ast) --> term(Ast1), expr_(Ast1,Ast).
expr_(Acc,Ast) --> " + ", !, term(Ast2), expr_(plus(Acc,Ast2), Ast).
expr_(Acc,Ast) --> " - ", !, term(Ast2), expr_(minus(Acc,Ast2), Ast).
expr_(Acc,Acc) --> [].

term(Ast) --> factor(Ast1), term_(Ast1,Ast).
term_(Acc,Ast) --> " * ", !, factor(Ast2), term_(mul(Acc,Ast2),Ast).
term_(Acc,Ast) --> " ** ", !, factor(Ast2), term_(pol(Acc,Ast2),Ast).
term_(Acc,Acc) --> [].

factor(Ast) --> "(", !, expr(Ast), ")".
factor(D)--> [X], { X >= 48 , X=<57 , D is X-48 }.
factor(id(N,E)) --> "x", factor(N), ":=", expr(E), ";".

例如:

?- parse("x2:=4",T).
T = id(2, 4)

没错!但是,当我写:

?- parse("x2 := 4",T).
false.

它也必须为真并且它应该是一个过滤器:kill_whitespace(Source, CleanInput)

不同的解决方案效率低下。我该怎么做?

最佳答案

我通常会在可能出现空格的地方放置一个“跳过”非终结符。这种跳过通常会丢弃评论以及任何其他“无趣”的文本。

尽可能简单:

% discard any number of spaces
s --> "" ; " ", s.

我更喜欢短名称,以保持语法清晰。也丢弃换行符等:

s --> "" ; (" ";"\t";"\n";"\r"), s.

“样式”注释:而不是

parse(Source, Tree) :-
expr(Tree, Source, []).

你可以考虑

parse(Source, Tree) :-
phrase(expr(Tree), Source).

关于string - 从 Prolog 中的字符串中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14366036/

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