How do you do a search and replace of a list with another sublist in Prolog?

前端 未结 2 1522
耶瑟儿~
耶瑟儿~ 2020-12-07 02:54

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,

2条回答
  •  佛祖请我去吃肉
    2020-12-07 03:16

    You can use append/2 as follows :

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

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

提交回复
热议问题