Prolog - 如何替换列表中的某些单词 [英] Prolog - How to replace certain words in a list

查看:42
本文介绍了Prolog - 如何替换列表中的某些单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下序言谓词:

processWords([hello, my, name, is, Simon], Result).

我需要知道如何获得:

Result = [bye, my, name, is, Ben]

我将如何遍历列表并返回替换hello"的字符串?用再见"和西蒙"与Ben"一起使用 Prolog?

How would I recurse through the list and return a string that replaces "hello" with "bye" and "Simon" with "Ben", using Prolog?

非常感谢任何帮助,谢谢!

Any help is greatly appreciated, thanks!

推荐答案

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

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

这篇关于Prolog - 如何替换列表中的某些单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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