当前位置:  开发笔记 > 编程语言 > 正文

以边界限制器为元素的子列表

如何解决《以边界限制器为元素的子列表》经验,为你挑选了1个好方法。

我有一个像这样的列表的基本谓词:

sublist(List, Offset, Length, Sublist)


sublist(List, Offset, Length, Sublist):-
    length(Prefix, Offset),
    append(Prefix, Rest, List),
    length(Sublist, Length),
    append(Sublist, _, Rest).

它从给定长度的初始列表中的第一个元素返回一个子列表.

6 ?- sublist([a,b,c,d,e,f,g,h,i,j,k], 3, 6, X).
X = [d, e, f, g, h, i].

我想用一个下限和上限来转换这个谓词,它直接是原始列表的元素,就像这样

sublist([a,b,c,d,e,f,g,h,i,j,k], d, i, X).
X = [d, e, f, g, h, i].

这该怎么做?



1> lurker..:

这不是现有代码的简单"转换",但理想情况下使用DCG处理:

% subseq(S, First, Last) succeeds if S is a subsequence of the input
%   sequence and starts with First and ends with Last.
%   The subsequence is defined as an arbitrary sequence (...)
%   followed by the desired subsequence, followed by another arbitrary sequence
%
subseq([First|T], First, Last) --> ..., seq([First|T], Last), ... .

% seq(S, X) defines any sequence that ends with X
%
seq([X], X) --> [X].
seq([H|T], X) --> [H], seq(T, X).

% ... defines an arbitrary sequence of zero or more input elements
%
... --> [].
... --> [_], ... .

% sublist(L, First, Last, S) succeeds if S is a subsequence of L that
%   starts with First and ends with Last. It works by calling the DCG
%   defined above.
%
sublist(L, First, Last, S) :- phrase(subseq(S, First, Last), L).

导致:

| ?- sublist([a,b,d,e,f,g,h,i,j,k], d, i, S).

S = [d,e,f,g,h,i] ? a

no

| ?- sublist([a,b,d,c,d,e,f,g,h,i,j,k], d, i, S).

S = [d,c,d,e,f,g,h,i] ? a

S = [d,e,f,g,h,i]

no
| ?-


另外,subseq//3可以略微改写为:

subseq([First|T], First, Last) --> seq(_, First), seq(T, Last), ... .


@false因为设计`seq/2`只有在序列中看到"最后一个元素"(因此,第二个参数)时才需要成功,而空序列没有最后一个元素.
推荐阅读
sx-March23
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有