Using a prolog DCG to find & replace - code review

北战南征 提交于 2019-12-10 17:17:10

问题


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

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?

Thanks in advance.


回答1:


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

Example:

?- substitute("a", "b", "atesta", R), atom_codes(A, R).
R = [98, 116, 101, 115, 116, 98],
A = btestb.

Also, underscores_are_much_more_readable thanMixedCaseNamesAsYouSee.




回答2:


About the second question, i.e. working with atoms, I wrote this utility perusing atomic_list_concat

%%  replace_word(+Old, +New, +Orig, -Replaced)
%%  is det.
%
%   string replacement
%   doesn't fail if not found
%
replace_word(Old, New, Orig, Replaced) :-
    atomic_list_concat(Split, Old, Orig),
    atomic_list_concat(Split, New, Replaced).

Example:

?- replace_word(a, b, atesta, X).
X = btestb.


来源:https://stackoverflow.com/questions/6392725/using-a-prolog-dcg-to-find-replace-code-review

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!