我在 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)
.
不同的解决方案效率低下。我怎样才能做到这一点?