为便于比较,sublist/2
Logtalk 库中使用的谓词定义为:
sublist(List, List).
sublist(Sublist, [Head| Tail]) :-
sublist(Tail, Head, Sublist).
sublist(Sublist, _, Sublist).
sublist([Head| Tail], _, Sublist) :-
sublist(Tail, Head, Sublist).
sublist([Head| Tail], Element, [Element| Sublist]) :-
sublist(Tail, Head, Sublist).
IIRC,这是一个常见的定义。一些示例调用可能是:
?- list::sublist(Sublist, [1,2,3]).
Sublist = [1, 2, 3] ;
Sublist = [2, 3] ;
Sublist = [3] ;
Sublist = [] ;
Sublist = [2] ;
Sublist = [1, 3] ;
Sublist = [1] ;
Sublist = [1, 2].
?- list::sublist([1,2], List).
List = [1, 2] ;
List = [_1376, 1, 2] ;
List = [_1376, _1382, 1, 2] ;
List = [_1376, _1382, _1388, 1, 2] ;
...
?- list::sublist(Sublist, List).
Sublist = List ;
List = [_1172|Sublist] ;
List = [_1172, _1178|Sublist] ;
List = [_1172, _1178, _1184|Sublist] .
...
更新
注意到问题中的定义和我的答案中的定义没有相同的语义。问题中的定义意味着连续的元素。例如
?- sublist(Sublist, [1,2,3]).
Sublist = [] ;
Sublist = [1] ;
Sublist = [1, 2] ;
Sublist = [1, 2, 3] ;
Sublist = [] ;
Sublist = [2] ;
Sublist = [2, 3] ;
Sublist = [] ;
Sublist = [3] ;
Sublist = [] ;
false.
此定义中的一个问题是多次生成空列表解决方案。