List Prolog在列表中复制一个单词
我有一个复制整个列表的Prolog代码,但我想要的是只复制一个单词(例如“a”)。比如,List Prolog在列表中复制一个单词,list,prolog,duplicates,List,Prolog,Duplicates,我有一个复制整个列表的Prolog代码,但我想要的是只复制一个单词(例如“a”)。比如, dups([],[]). dups([H|T],[H,H|Y]) :- dups(T,Y). 我的代码重复列表[a,b]类似=>[a,a,b,b] 但我想要的是,重复列表[a,b]像=>[a,a,b]既然您正在描述列表,您可以选择使用DCG。考虑以下规则: x_dup(_X,[]) --> % if the input list is empty [].
dups([],[]).
dups([H|T],[H,H|Y]) :-
dups(T,Y).
我的代码重复列表[a,b]
类似=>[a,a,b,b]
但我想要的是,重复列表
[a,b]
像=>[a,a,b]
既然您正在描述列表,您可以选择使用DCG。考虑以下规则:
x_dup(_X,[]) --> % if the input list is empty
[]. % the output list is empty
x_dup(X,[X|Ys]) --> % if X and the head of the list are equal
[X,X], % X is twice in the output list
x_dup(X,Ys). % the same holds for X and the tail
x_dup(X,[Y|Ys]) --> % if X and the head of the input list
{dif(X,Y)}, % are different
[Y], % the head is once in the output list
x_dup(X,Ys). % the same holds for X and the tail
如果您只想复制列表的开头,可以这样定义调用谓词:
dups([],[]). % <- only for empty list
dups([X|Xs],L) :-
phrase(x_dup(X,[X|Xs]),L).
或者,您可以定义调用谓词,以便可以复制任意元素。在这种情况下,您需要一个附加参数来指定要复制的元素:
dups(X,L1,L2) :-
phrase(x_dup(X,L1),L2).
一些示例查询:
?- dups(a,[a,b,a,a,c,c,c],L).
L = [a,a,b,a,a,a,a,c,c,c] ? ;
no
?- dups(b,[a,b,a,a,c,c,c],L).
L = [a,b,b,a,a,c,c,c] ? ;
no
?- dups(c,[a,b,a,a,c,c,c],L).
L = [a,b,a,a,c,c,c,c,c,c] ? ;
no
?- dups(d,[a,b,a,a,c,c,c],L).
L = [a,b,a,a,c,c,c]
只有第一个元素?还是要回溯,从而为每个元素生成一个列表?我想要的是复制列表中的每个“a”字符。例如abaacc=>aabaaacct感谢您的回复:)
?- dups(a,[a,b,a,a,c,c,c],L).
L = [a,a,b,a,a,a,a,c,c,c] ? ;
no
?- dups(b,[a,b,a,a,c,c,c],L).
L = [a,b,b,a,a,c,c,c] ? ;
no
?- dups(c,[a,b,a,a,c,c,c],L).
L = [a,b,a,a,c,c,c,c,c,c] ? ;
no
?- dups(d,[a,b,a,a,c,c,c],L).
L = [a,b,a,a,c,c,c]