问题描述
我想出了以下代码来替换 Request
中所有出现的 Find
w/Replace
&将答案放在 Result
中.这是使用 DCG,因此它们都是字符代码列表.客户端代码将使用的谓词是 substitute
.
I came up w/ the following code to replace all occurences of Find
w/ Replace
in Request
& put the answer in Result
. This is using a DCG, so they are all lists of character codes. The predicate that client code would use is substitute
.
findReplace(_, _, [], []) -->
[]. % The end.
findReplace(Find, Replace, Result, ResultRest) -->
Find, % Found Find.
{ append(Replace, Intermediate, Result) }, % Put in Replace in Find's place.
!, % Make sure we don't backtrack & interpret Find as the next case.
findReplace(Find, Replace, Intermediate, ResultRest).
findReplace(Find, Replace, [ C | Intermediate ], ResultRest) -->
[ C ], % Any other character.
findReplace(Find, Replace, Intermediate, ResultRest).
substitute(Find, Replace, Request, Result):-
phrase(findReplace(Find, Replace, Result, []), Request).
这适用于 SWI-Prolog.有没有人对我如何改进它有任何意见?我正在学习如何使用 DCG 的 &差异列表.例如,我加入了剪辑,以便在找到 Find
后,prolog 永远不会回溯 &在 [ C ]
情况下将其解释为普通字符.这是必要的,还是有更声明性的方法?
This works in SWI-Prolog. Does anyone have any comments on how I could improve it? I'm learning how to use DCG's & difference lists. E.g., I put in the cut so that, after finding Find
, prolog doesn't ever backtrack & interpret that as an ordinary character in the [ C ]
case. Is this needed, or is there a more declarative way of doing so?
另一个问题 - 是否有一个谓词已经可以用来做与替代相同的事情,也许是在原子上?
Another question - is there a predicate already available to do the same thing that substitute does, maybe on atoms?
提前致谢.
推荐答案
考虑使用半上下文表示法来替换 DCG 中的子序列:
Consider using semicontext notation to replace subsequences in DCGs:
eos([], []).
replace(_, _) --> call(eos), !.
replace(Find, Replace), Replace -->
Find,
!,
replace(Find, Replace).
replace(Find, Replace), [C] -->
[C],
replace(Find, Replace).
substitute(Find, Replace, Request, Result):-
phrase(replace(Find, Replace), Request, Result).
示例:
?- substitute("a", "b", "atesta", R), atom_codes(A, R).
R = [98, 116, 101, 115, 116, 98],
A = btestb.
此外,underscores_are_much_more_readable thanMixedCaseNamesAsYouSee.
Also, underscores_are_much_more_readable thanMixedCaseNamesAsYouSee.
这篇关于使用 prolog DCG 查找 &替换 - 代码审查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!