我正在努力解决这个问题:
定义谓词
len_NM(L,N,M)
,用于检查某个列表L
是否至少包含长度不小于N
的{{1}}个元素。
答案 0 :(得分:1)
OP说:
定义谓词
len_NM(L,N,M)
,用于检查某个列表L
是否包含至少N
个元素,且长度不小于M
。
在这个答案中,我们没有解决原始问题,但有以下变化:
定义谓词
len_NM(L,N,M)
,用于检查某个列表L
是否包含长度不小于N
的完全M
个元素。< / p>
与this answer类似,我们定义dcg seqq1//1
来建立非空列表列表与其相反的平面列表之间的关系:
seq([]) --> []. seq([E|Es]) --> [E], seq(Es). seqq1([]) --> []. seqq1([Es|Ess]) --> {Es=[_|_]}, seq(Es), seqq1(Ess).
样品使用:
?- phrase(seqq1([[1,2],[3],[4]]),Xs).
Xs = [1,2,3,4].
请注意,seqq1//1
适用于“双向”:
?- phrase(seqq1(Xss),[1,2,3,4]).
Xss = [[1],[2],[3],[4]]
; Xss = [[1],[2],[3,4]]
; Xss = [[1],[2,3],[4]]
; Xss = [[1],[2,3,4]]
; Xss = [[1,2],[3],[4]]
; Xss = [[1,2],[3,4]]
; Xss = [[1,2,3],[4]]
; Xss = [[1,2,3,4]]
; false.
在这个答案中,我们使用clpfd:
:- use_module(library(clpfd)).
然后,我们定义len_NM/4
- 使用maplist/3
,
length/2
,tcount/3
和(#=<)/3
:
len_NM(Xss,Ys,N,M) :-
M #>= 1,
N #>= 0,
phrase(seqq1(Xss),Ys),
maplist(length,Xss,Ls),
tcount(#=<(M),Ls,N).
让我们运行一些示例查询!
?- len_NM([[1,2,3],[4],[5,6],[7,8,9,10],[11,12]],_,N,L).
N = 5, L = 1 % five lists have length of at least one
; N = 4, L = 2 % four lists have length of at least two
; N = 2, L = 3 % two of at least three (e.g., [1,2,3] and [7,8,9,10])
; N = 1, L = 4 % one list has length of four (or more)
; N = 0, L in 5..sup. % no list has length of five (or more)
OK!这个怎么样?
?- append(Xs,_,[x,x,x,x,x,x]), % With `Xs` having at most 6 elements ...
N #>= 1, % ... `Xss` shall contain at least 1 list ...
len_NM(Xss,Xs,N,4). % ... having a length of 4 (or more).
Xs = [x,x,x,x], N = 1, Xss = [[x,x,x,x]]
; Xs = [x,x,x,x,x], N = 1, Xss = [[x],[x,x,x,x]]
; Xs = [x,x,x,x,x], N = 1, Xss = [[x,x,x,x],[x]]
; Xs = [x,x,x,x,x], N = 1, Xss = [[x,x,x,x,x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x],[x],[x,x,x,x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x],[x,x,x,x],[x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x],[x,x,x,x,x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x,x],[x,x,x,x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x,x,x,x],[x],[x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x,x,x,x],[x,x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x,x,x,x,x],[x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x,x,x,x,x,x]]
; false.