I am trying to solve a simple prolog question but I am not able to solve it. From a list a need to create a sublist given the index I and then from I the next elements given as N. If the index is greater than the list lenght I will get the sublist empty. If N (number of elements) is greater than the rest of elements in the list I will get all the elements from I until the end.
Here, I got one part of the assignment, I can get from the index I, the next elements N. Now I ask about the other parts in the assignment:
1) When I
(index) is longer than the list length, I have to get an empty list in the sublist.
?- sublist([a,b,c,d],5,2,L)
L=[]
2) When N
(Next elements) is greater than the number of elements we have rest, I need to get all the elements from that position till the end.
?- sublist([a,b,c,d],4,4,L)
L=[d]
The code I already have is the next one, this one is working:
sublist([X|_],1,1,[X]).
sublist([],_,_,[]).% I use this one for the case bases
sublist([X|Xs],1,K,[X|Ys]):-
K>1,
K1 is K-1,
sublist(Xs,1,K1,Ys).
sublist([_|Xs],I,K,Ys):-
I > 1,
I1 is I-1,
sublist(Xs,I1,K,Ys).