I am trying to keep only the first element and the last element for a list which contains only consecutive integers.
For example:
?- remove([1,2,3,4,5], NewList).
NewList = [1,5].
I can only successfully keep the last element:
remove([], []).
% for consecutive integers in the list
remove([ Head | Tail ], NewList) :-
check_consecutive(Head, Tail),
remove(Tail, NewList).
% for the case when the list is empty
remove([ Head | Tail ], [ Head | NewList ]) :-
not(check_consecutive(Head, Tail)),
remove(Tail, NewList).
check_consecutive(Num, [ Head | _ ]) :-
Num is Head - 1.
I have been tying to keep the first element, but it keeps giving me the last element.
If there are some elements which is not consecutive, it should do some thing like:
?- remove([1,2,4,5,6,8,3], NewList).
NewList = [[1,6], 8, 3].
Any assistance is appreciated.
To solve this problem you have to handle different cases, here the solution then the comment:
So, first of all, i've defined
last/2
that simply, given a list as an input, returns the last elementThen with
remove/3
i get the list composd by th first and the last element.findElements/2
is used to call findElementsR/4 (to make it tail recursive).findElements/4
finds a list of consecutive elements and then callsremove/2
to get the first and the last.