我目前正在Prolog程序中使用它:
sublist(X, L) :- append(_, S, L), append(X, _, S).
如果我这样称呼它,它将正确列出列表的子列表,
?- sublist(A, [1, 2, 3]).
A = [] ;
A = [1] ;
A = [1, 2] ;
A = [1, 2, 3] ;
A = [] ;
A = [2] ;
A = [2, 3] ;
A = [] ;
A = [3] ;
A = [] ;
false.
我希望制作一个新功能,首先尝试所有较短的子串,以便它能够提供更像
的东西。[1] ; [2] ; [3] ; [1, 2] ; [2, 3] ; [1, 2, 3].
取出空列表并不重要,但会更受欢迎。
答案 0 :(得分:2)
其中一个following怎么样?使用SWI-Prolog我们定义以下规则:
版本1
sublist_of([X|Xs], [E|Es]) :- append(Ruler, _, [E|Es]), % ensure we get answers in ascending lengths same_length(Ruler, [X|Xs]), append([_,[X|Xs],_], [E|Es]).
版本2
sublist_of__ver2([X|Xs], [E|Es]) :- append(Ruler, _, [E|Es]), % ensure we get answers in ascending lengths same_length(Ruler, [X|Xs]), append([_,[X|Xs],_], [E|Es]).
版本3a
sublist_of__ver3a([X|Xs], [E|Es]) :- len1_len2_len12([X|Xs], _, [E|Es]), append([_,[X|Xs],_], [E|Es]). len1_len2_len12([], Ys, Zs) :- same_length(Ys, Zs). len1_len2_len12([_|Xs], Ys, [_|Zs]) :- len1_len2_len12(Xs, Ys, Zs).
版本3b
sublist_of__ver3b(Xs, Es) :- Xs = [_|_], len1_len2_len12(Xs, _, Es), append([_,Xs,_], Es).
OP给出的示例查询:
?- sublist_of__ver2(Xs, [1,2,3,4]). Xs = [1 ] ; Xs = [ 2 ] ; Xs = [ 3 ] ; Xs = [ 4] ; Xs = [1,2 ] ; Xs = [ 2,3 ] ; Xs = [ 3,4] ; Xs = [1,2,3 ] ; Xs = [ 2,3,4] ; Xs = [1,2,3,4] ; false.
答案 1 :(得分:0)
为了便于阅读,我交换了参数顺序 - 请原谅我:)
sublist(L, S) :-
length(L, N),
between(1, N, M),
length(S, M),
append([_,S,_], L).
产量
?- sublist([a,b,c],S).
S = [a] ;
S = [b] ;
S = [c] ;
S = [a, b] ;
S = [b, c] ;
S = [a, b, c] ;
false.
答案 2 :(得分:0)
Sicstus-prolog
sublist(?X,+List).
library(lists3).
内的% sublist(?Sub, +List)
% is true when all members of Sub are members of List
:- sublist(?,+) is nondet.
sublist(List, List).
sublist(Sub, [Head|Tail]) :- sublist_(Tail, Head, Sub).
:- sublist_/3 is nondet.
sublist_(Sub, _, Sub).
sublist_([Head|Tail], _, Sub) :- sublist_(Tail, Head, Sub).
sublist_([Head|Tail], X, [X|Sub]) :- sublist_(Tail, Head, Sub).
<强>码强>
?- sublist(Y,[1,2,3]).
Y = [1,2,3] ? ;
Y = [2,3] ? ;
Y = [3] ? ;
Y = [] ? ;
Y = [2] ? ;
Y = [1,3] ? ;
Y = [1] ? ;
Y = [1,2] ? ;
no
结果
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.2.Final</version>
</dependency>