我有一个像这样的列表的基本谓词:
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].
这该怎么做?
这不是现有代码的简单"转换",但理想情况下使用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), ... .