在prolog中定义谓词

时间:2015-05-15 13:11:17

标签: list prolog

我正在努力解决这个问题:

  

定义谓词len_NM(L,N,M),用于检查某个列表L是否至少包含长度不小于N的{​​{1}}个元素。

1 个答案:

答案 0 :(得分:1)

  1. OP说:

      

    定义谓词len_NM(L,N,M),用于检查某个列表L是否包含至少 N个元素,且长度不小于M

  2. 在这个答案中,我们没有解决原始问题,但有以下变化:

      

    定义谓词len_NM(L,N,M),用于检查某个列表L是否包含长度不小于N完全 M个元素。< / p>

  3. this answer类似,我们定义 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.
    
  4. 在这个答案中,我们使用

    :- use_module(library(clpfd)).
    

    然后,我们定义len_NM/4 - 使用maplist/3length/2tcount/3(#=<)/3

    len_NM(Xss,Ys,N,M) :-
       M #>= 1,
       N #>= 0,
       phrase(seqq1(Xss),Ys),
       maplist(length,Xss,Ls),
       tcount(#=<(M),Ls,N).
    
  5. 让我们运行一些示例查询!

    ?- 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.