问题描述
基本上,我需要创建一个形式为 sublist(S,M,N,L) 的谓词,其中 S 是由 L 的元素在索引 M 和索引 N 之间(含)形成的新列表.
Basically, I need to create a predicate of the form sublist(S,M,N,L), where S is a new list formed from the elements of L between index M and index N, inclusive.
这是我得到的:
sublist([],_,_,[]).
sublist([],M,N,_) :- (M > N).
sublist(S,M,N,L) :- sublist2(S,M,N,L,-1).
sublist2([H|T],St,En,[H2|T2],Idx) :-
(Idx2 is Idx + 1,
St =< Idx2,
En >= Idx2,
H = H2,
sublist2(T,St,En,T2,Idx2);
Idx2 is Idx + 1,
sublist2(T,St,En,T2,Idx2)).
和我所有的序言问题一样,我觉得我把它弄得比它应该的复杂.我的基本情况是正确的,但其他任何评估都为假.关于这个问题的任何建议,以及序言的一般方法?我大部分都懂语言,但我似乎看不到简单的解决方案.
As with all my prolog problems, I feel I'm making it way more complicated than it should be. I've got the base cases right, but anything else evaluates to false. Any advice for this problem, and just general approach to prolog? I understand the language for the most part, but I can't seem to see the simple solutions.
推荐答案
简单的解决方案遵循简单的前景.对于列表,它是递归的.递归编程很简单——想象一下你已经有了你的函数,遵循给定的接口/要求,所以你可以随时使用它(但在简化的情况下更好).
Simple solutions follow simple outlook. For lists it's recursion. Recursive programming is simple - just imagine you already have your function, following the given interface/requirements, and so you get to use it whenever you feel like it (but better, in the reduced cases).
sublist(S,M,N,[_A|B]):- M>0, M<N, sublist(S,M-1,N-1,B).
将其视为子列表定律的陈述:较短列表中的子列表从减少的索引开始.
think of it as stating a law of sublists: sublist in a shorter list starts at decreased index.
sublist(S,M,N,[A|B]):- 0 is M, M<N, N2 is N-1, S=[A|D], sublist(D,0,N2,B).
和,
sublist([],0,0,_).
它在第二个索引中是独占的.调整它.:)
it is exclusive in the second index. tweak it. :)
这篇关于Prolog:创建子列表,给定两个索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!