I am trying to make use of prolog predicates and find middle element of a given list. My idea was to cut first and last element of list using recursion.Unfortunately I dont know how to handle recursion call properly.
delete_last(L, L1) :-
append(L1, [_], L).
delete_first(L,L1) :-
append([_],L1,L).
check_len(L) :-
length(L,LEN), \+ 1 is LEN.
delete_both([],_):-
false.
delete_both([_,_],_) :-
false.
delete_both([X],X):-
true, write('MidElement').
delete_both(L,L2) :-
delete_first(LT,L2), delete_last(L,LT),check_len(LT)
->write('here should be recursive call only when length is more than one').
I would be grateful for any help.
You can tighten up what you have quite a bit as follows:
With results:
A DCG solution also works well here:
With results:
Another possible solution is to use SWI Prolog's
append/2
predicate, which appends a list of lists (assuming you're using SWI):In all of the above solutions, the predicate fails if the list has an even number of elements. Since that's what your original solution does, I assumed that's what is required. If there is a specific requirement for even lists, that needs to be stated clearly.
It would save a lot of typing if you checked the length of the list, calculated the position of the middle element, and only then traversed the list to get the element at that position. With SWI-Prolog, this would be:
This solution makes sure the list has an odd length. You can see the documentation of
divmod/4
if you need to define it yourself. Or, if the list does not have to have and odd, length, just useN is Len div 2
. If for some reason you are not allowed to usenth0/3
, it is still an easier predicate to implement than what you are trying to do.