且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Prolog - 如何替换列表中的某些单词

更新时间:2023-11-25 23:31:22

首先,这是不可能的,因为西蒙"和本"在你的例子中是变量.但假设你对西蒙"没问题和本",这是一个答案:

First of all, this cannot be done, since "Simon" and "Ben" in your example are variables. But supposing you are fine with "simon" and "ben", here is an answer:

processWords([], []).

processWords([H|T], [H2|T2]) :-
    translate(H, H2),
    processWords(T, T2).

translate(hello, bye):-!.
translate(simon, ben):-!.
translate(X, X). % catch-all clause for all words not to be translated

或者,您可以使用 maplist/3:

processWords(L,L2):-maplist(translate, L, L2).

translate(hello, bye):- !.
translate(simon, ben):- !.
translate(X, X). % catch-all clause for all words not to be translated