有人可以帮助我使用Sublist Predicate(Prolog)吗?

时间:2017-04-14 13:10:03

标签: prolog sublist

我想实现一个谓词子列表1(I1,I2,L,Sub),它接受列表L并返回包含从索引I1到索引I2的L元素的Sub。 我的代码一直给我假。 任何想法出了什么问题?

sublist1(0,0,[H|T],[H|Sub]).


sublist1(I1,I2,[H|T],Sub):-
   I1 =0, I2>=I1,
   I is I2-1,
   sublist1(I1,I,T,[H|Sub]).

sublist1(I1,I2,[H|T],_):-
  I1>0, I2>I1,
  II1 is I1-1,
  II2 is I2-1,
  sublist1(II1,II2,T,_).

1 个答案:

答案 0 :(得分:1)

在算法上,我会说这应该有效:

% sublist from 0 to 0 should return [H] for any List
sublist1(0,0,[H|T],[H]).

% sublist from 0 to n should return the first element followed with the sublist from 0 to n-1 of the tail
sublist1(I1,I2,[H|T],[H|Sub]):-
    I1 is 0, I2 > 0,
    II2 is I2 - 1,
    sublist1(I1,II2,T,Sub).

% sublist of [H|T] from I1 to I2 should return the sublist from I1-1 to I2-1 of T
sublist1(I1,I2,[H|T],Sub):-
  I1>0, I2>I1,
  II1 is I1-1,
  II2 is I2-1,
  sublist1(II1,II2,T,Sub).

修改

Try it online(例如,运行执行并编写sublist1(2,5,[0,1,2,3,4,5,6,7,8],S).)。 对alt+91使用[alt+93

使用]