首页 > 解决方案 > 谓词在列表中有三次?

问题描述

如果列表包含一个元素的 3 个副本,我正在编写一个谓词以打印 true 并打印该元素。此外,谓词应该打印替代解决方案(如果存在)。

我写的谓词-

hasTriplicate(List):-hasTriplicateAcc(List,Element,0).

%hasTriplicateAcc is wrapped by predicate hasTriplicate since I wanted the arity of hasTriplicate to be 1.

hasTriplicateAcc(_,Element,3):-write(Element).
hasTriplicateAcc([H|T],H,Ct):-hasTriplicateAcc(T,H,Ct1),Ct1 is Ct+1.
hasTriplicateAcc([Z|T],H,Ct):-hasTriplicateAcc(T,H,Ct),Z=\=H.

输出

hasTriplicate([1,1,1]).
11
ERROR: Arguments are not sufficiently instantiated
ERROR: In:
ERROR:   [11] 3 is _10188+1
ERROR:   [10] hasTriplicateAcc([1,1],1,_10218) at c:/users/user/desktop/code/hastriplicate.pl:3
ERROR:    [9] hasTriplicateAcc([1,1|...],1,0) at c:/users/user/desktop/code/hastriplicate.pl:3
ERROR:    [7] <user>
ERROR: 
ERROR: Note: some frames are missing due to last-call optimization.
ERROR: Re-run your program in debug mode (:- debug.) to get more detail.
Exception: (10) hasTriplicateAcc([1, 1], 1, _10332)

我不明白这个错误。如果有人告诉我如何更正谓词的代码,那就太好了。

标签: prolog

解决方案


我认为这个解决方案会奏效。

hascountminimal(_,_,0):-true,!.
hascountminimal([E|L],E,N):- ! , N1 is N - 1 , N >= 1 , hascountminimal(L,E,N1) .
hascountminimal([_|L],E,N):- hascountminimal(L,E,N).


intripple(L,E):-hascountminimal(L,E,3),write(E).

推荐阅读