在Prolog中从字符串中删除空格 [英] Removing whitespace from strings in Prolog

查看:103
本文介绍了在Prolog中从字符串中删除空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Prolog中编写了解析器.我还没吃完它是代码的一部分.下一步是杀死字符串中的所有空格.

I wrote parser in Prolog. I haven't finished yet. It is a part of code. The next step is killing all whitespace in string.

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).

It must be true as well and it should be a filter: kill_whitespace(Source, CleanInput).

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

Different solutions are inefficient. How can I do that?

推荐答案

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

I usually place a 'skip' non terminal where space can occurs. Such skip usually discards comments as well as any other 'uninteresting' text.

要尽可能简化:

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

我更喜欢用一个简短的名字来保持语法的简洁.还要删除换行符等.

I prefer a short name, to keep the grammar clean. To discard newlines etc.. as well:

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

样式"注释:代替

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

您可以考虑

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

这篇关于在Prolog中从字符串中删除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆