在 Prolog 中查找所有大小为 N 的子列表

Finding all sublists of size N in Prolog

我是 Prolog 的新手,我在编写这个谓词时遇到了困难。基本上我得到了一个列表,我需要找到最常见的大小为 N 的子列表。示例:

  1. most_common_sublist([1,2,2,3,2,2,4,2,2,3],1,L),输出应该是L=[2]

  2. most_common_sublist([1,2,2,3,2,2,4,2,2,3],2,L),输出应该是L=[2,2]

  3. most_common_sublist([1,2,2,3,2,2,4,2,2,3],3,L),输出应该是L=[2,2,3]

我的方法是编写一个谓词来获取列表的前 N ​​个元素,编写第二个谓词,它将像生成器一样工作(一遍又一遍地调用第一个谓词,直到列表缩短到大小 N),然后检查所有生成的子列表有多少次匹配并获得最大值。

我卡在了生成器谓词上,剩下的我很确定我知道怎么写。

到目前为止,这是我的代码:

length([],0).
length([_|L],N) :- N is M+1, length(L,M).

// This will get the first N elements from the list. 
// I tested it and it works.
sublist([H|_],1,[H]).
sublist([H|T],N,[H|LOP]) :- M is N-1, sublist(T,M,LOP).

// This is supposed to generate all the sublists, 
// length is a predicate that returns the length of the list. 
generator(L,N,L) :- length(L,M), N=:=M.
generator([H|T],N,[PN|LOP]) :- sublist([H|T],N,PN), generator(T,N,LOP).

这是我遇到的错误:

?- generator([1,2,3,4,5,6,7],2,X).
ERROR: Arguments are not sufficiently instantiated
ERROR: In:
ERROR:   [12] _6018 is _6024+1
ERROR:   [11] length([1,2|...],_6052) at c:/users/ace_m/documents/prolog/bp.pl:44
ERROR:   [10] generator([1,2|...],2,[1,2|...]) at c:/users/ace_m/documents/prolog/bp.pl:83
ERROR:    [9] <user>
   Exception: (10) generator([1, 2, 3, 4, 5, 6, 7], 2, _5204) ? 

我知道这个错误意味着我没有传递正确的值,但我不明白我哪里出错了。任何帮助

在变量绑定到一个值之前,您不能在算术表达式中使用它。