您如何在 Prolog 中使用另一个子列表搜索和替换列表? [英] How do you do a search and replace of a list with another sublist in Prolog?

查看:34
本文介绍了您如何在 Prolog 中使用另一个子列表搜索和替换列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过搜索和替换来修改列表,想知道如何使用搜索词作为列表搜索列表?

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?

假设我有一个列表 [1,2,3,4] 我想挑出 2 和 3 并用 5,6 替换它所以理想情况下我可以有一个谓词:

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

推荐答案

您可以使用 append/2 如下:

replace(ToReplace, ToInsert, List, Result) :-
    once(append([Left, ToReplace, Right], List)),
    append([Left, ToInsert, Right], Result).

使用或不使用 once/1 取决于您是否想要所有的可能性.

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 :

replace(ToReplace, ToInsert, List, Result) :-
    replace(ToReplace, ToInsert, List, [], Result).
replace(ToReplace, ToInsert, List, Acc, Result) :-
    append([Left, ToReplace, Right], List),
    append([Acc, Left, ToInsert], NewAcc),
    !,
    replace(ToReplace, ToInsert, Right, NewAcc, Result).
replace(_ToReplace, _ToInsert, [], Acc, Acc).

这篇关于您如何在 Prolog 中使用另一个子列表搜索和替换列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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