List Prolog-将列表中X个元素替换为顺序为I的元素
我试图实现一个谓词,它在给定索引之后(包括)替换列表的NumElm元素。为此,我使用另一个谓词替换列表中的一个元素。 到目前为止,我的代码是:List Prolog-将列表中X个元素替换为顺序为I的元素,list,replace,prolog,elements,List,Replace,Prolog,Elements,我试图实现一个谓词,它在给定索引之后(包括)替换列表的NumElm元素。为此,我使用另一个谓词替换列表中的一个元素。 到目前为止,我的代码是: replace([_|T], 0, X, [X|T]). replace([H|T], I, X, [H|R]):- I > -1, NI is I-1, replace(T, NI, X, R), !. replace(L, _, _, L). replaceX(_,_,0,_,_). replaceX(Line,Index,Nu
replace([_|T], 0, X, [X|T]).
replace([H|T], I, X, [H|R]):-
I > -1,
NI is I-1,
replace(T, NI, X, R), !.
replace(L, _, _, L).
replaceX(_,_,0,_,_).
replaceX(Line,Index,NumElm,Elm,NLine) :-
replace(Line,Index,Elm,BLine),
Index1 is Index+1,
NumElm1 is NumElm-1,
replaceX(BLine,Index1,NumElm1,Elm,Nline).
使用该代码,只替换第一个元素,order Index元素。
有什么想法吗?
提前谢谢。
[编辑]前面代码的结果只是“是”。替换第一个元件的元件如下所示:
replace([_|T], 0, X, [X|T]).
replace([H|T], I, X, [H|R]):-
I > -1,
NI is I-1,
replace(T, NI, X, R), !.
replace(L, _, _, L).
replaceX(_,_,0,_,_).
replaceX(Line,Index,NumElm,Elm,NLine) :-
replace(Line,Index,Elm,NLine),
Index1 is Index+1,
NumElm1 is NumElm-1,
replaceX(NLine,Index1,NumElm1,Elm,Nline).
我会写道,在Prolog中处理数字索引可能会很乏味
replace(L, From, To, X, R) :-
findall(S, (nth0(I,L,E), (I>=From, I<To ->S = X ; S = E)), R).
我认为您需要用以下内容定义replaceX的第一个子句:
replaceX(A,_,0,_,A):-!.
这背后的原因可以通过\uuu
的工作原理来解释:它命名一个匿名变量,而\uu
的每个实例命名一个不同的变量。解释。另一方面,切割可以帮助你摆脱不必要的回溯
我认为最后一行的Nline
应该是Nline
。另外,在第二个replace
子句的末尾缺少一个点
编辑:
输入示例:
?- replaceX([0,1,2,3,4,5,6],2,4,a,R).
R = [0,1,a,a,a,a,6].
这不是预期的结果吗?这里有一种方法:
replace( As , _ , 0 , _ , As ) . % special case: nothing left to replace.
replace( [A|As] , P , N , X , [A|Bs] ) :- % otherwise,
P > 0 , % - if the position counter is greater than zero,
P1 is P-1 , % - decrement it, stow the current item to the result list
replace( As , P1 , N , X , Bs ) % - and recurse down
. %
replace( [_|As] , 0 , N , X , [X|Bs] ) :- % otherwise, if the position count is decremented to zero
N > 0 , % - but the length counter is greater than zero,
N1 is N-1 , % - decrement it, stow X in the result list
replace( As , 0 , N1 , X , Bs ) % - and recurse down.
. %
不幸的是,我还没有学会这个语法,所以我不确定我是否能使用它。谢谢,你的意思是增加那个条款还是用你的条款取代我的条款?不管怎样,输出都是肯定的。取代你的。我将编辑以包含代码。你正在使用的口译员是什么?我知道巴西的大多数大学都使用SWI prolog,这就是我测试的
?- replaceX([0,1,2,3,4,5,6],2,4,a,R).
R = [0,1,a,a,a,a,6].
replace( As , _ , 0 , _ , As ) . % special case: nothing left to replace.
replace( [A|As] , P , N , X , [A|Bs] ) :- % otherwise,
P > 0 , % - if the position counter is greater than zero,
P1 is P-1 , % - decrement it, stow the current item to the result list
replace( As , P1 , N , X , Bs ) % - and recurse down
. %
replace( [_|As] , 0 , N , X , [X|Bs] ) :- % otherwise, if the position count is decremented to zero
N > 0 , % - but the length counter is greater than zero,
N1 is N-1 , % - decrement it, stow X in the result list
replace( As , 0 , N1 , X , Bs ) % - and recurse down.
. %