如何在 Prolog 中搜索并用另一个子列表替换一个列表?
我正在尝试通过搜索和替换来修改列表,想知道如何使用搜索词作为列表来搜索列表?
假设我有一个列表 [1,2,3,4] 我想挑出 2 和 3 并将其替换为 5,6 所以理想情况下我可以有一个谓词:
search_and_replace(Search_Term, Replace_Term, Target_List, Result_List).
eg.
search_and_replace([2,3], [5,6], [1,2,3,4], Result_List), write(Result_List).
I'm trying to modify a list by search and replace, was wondering how do I search through a list with the search term as a list as well?
Lets say I have a list [1,2,3,4] I want to single out the 2 and 3 and replace it with 5,6
so ideally I could have a predicate:
search_and_replace(Search_Term, Replace_Term, Target_List, Result_List).
eg.
search_and_replace([2,3], [5,6], [1,2,3,4], Result_List), write(Result_List).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让我假设您想用另一个列表替换列表中的
subsequence子字符串。以下是执行此操作的一般方法。您可能想要插入
进一步的条件纳入该计划。
而且,是的,这可以稍微优化 - 甚至它的终止属性
会获利。但概念清晰性是非常宝贵的价值......
编辑:您的示例查询:
Let me assume that you want to replace a
subsequencesubstring within a list by another list.Here is a general way how to do this. You might want to insert
further conditions into the program.
And, yes this can be optimized a bit - even its termination property
would profit. But conceptual clarity is a quite precious value...
Edit: Your example query:
您可以按如下方式使用 append/2 :
使用或不使用 once/1 取决于您是否想要所有可能性。
为了替换所有发生的情况,我会用类似的东西:
You can use append/2 as follows :
With or without use of once/1 depending on if you want all the possibilies or not.
To replace all the occurences I'd go with something like :