Reputation: 11
I want to implement a predicate sublist1(I1,I2,L,Sub) that takes list L and returns Sub that includes elements of L from index I1 to index I2. My code gives me false all the time . Any Idea what's wrong?
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,_).
Upvotes: 1
Views: 94
Reputation: 4515
Algorithmically, I would say this should work :
% 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 (run execute and write sublist1(2,5,[0,1,2,3,4,5,6,7,8],S).
for example).
Use alt+91
for [
and alt+93
for ]
Upvotes: 1