我试图构建一个谓词itrepeats(all,part,num0,num)
"all"是“部件”列表的完整重复列表。"num"是“ in ”所有“”和"num0"的重复次数,“num”E 215
例如:
itrepeats(['a','b','c','a','b','c','a','b','c'],['a','b','c'],0,R)
产出应是:
R=3
另一个例子是:
itrepeats(['a','b','c','c','a','b','a','b','b'],['a','b','c'],0,R)
产出应是:
no
"all"空的另一个示例:
itrepeats([],['a','b','c'],0,R)
产出应是:
R=0
我试过这样做,但它不起作用,即使只是针对两个元素的列表:
itrepeats([],[_],0,0).
itrepeats([A,B|R],[A,B|R2],0,N):-
N is N-1,
itrepeats(R,[A,B|R2],0,N).
我确信应该是这样的,在"all"为空之前,在没有实际迭代的前一个元素的情况下执行下一个迭代,但我不知道如何做好它。帮帮忙,谢谢。
发布于 2021-05-12 12:40:15
这可能对你有帮助。
一个常见的Prolog成语是使用带有附加状态的助手谓词作为额外的参数。在这里,我们需要一个累加器来计数匹配的子列表,我们用0作为初始值进行种子:
number_of_sublists( [H|T] , SL , N ) :- number_of_sublists( [H|T], SL, 0, N ).
如果找到匹配的子列表,这个过程非常简单:
如果所需的子列表为当前列表的前缀,则将计数标记为1。
。
要找出一个列表是否是另一个列表的前缀很容易。只需匹配列表项,直到一个列表为空。(请注意,空列表将作为每个列表的前缀。)
is_prefix_of( [] , _ ). % once the prefix list is empty, we're done: the prefix list is the prefix of the other list.
is_prefix_of( [X|Xs] , [X|Ys] ) :- % Otherwise, if the two lists share a common head,
is_prefix_of(Xs, Ys). % - then recurse down on the tails.
把所有的东西组合在一起:
number_of_sublists( [] , _ , N , N ) . % once the list is exhausted, we're done. The accumulator is the final tally.
number_of_sublists( [H|T] , SL , X , N ) :- % otherwise...
( is_prefix_of(SL, [H|T]) % - if the sublist is a prefix of the list
-> X1 is X+1 % - then increment the accumulator by 1
; X1 is X % - else don't increment
), %
number_of_sublists( T, SL, X1, N ). % remove the head of the list and recurse down on its tail.
您可能会注意到,使用findall/3
和append/3
可以更容易地完成这一任务,比如:
number_of_sublists( L, SL, N ) :- findall( SL , prefix_of(SL,L), Sls), length(SLs,N).
prefix_of( SL, L ) :-
append( _ , Sfx , L ) ,
append( SL , _ , Sfx ).
https://stackoverflow.com/questions/67507544
复制相似问题