I am trying to write a function in Scheme and Prolog that returns first, middle and last item of a list. E.g., find([4,5,8,7,9],L), L = [4,8,9]
.
I came up w
Assuming that in the case that the list has even number of items you can choose one of them (in this case the first one), this procedure should work:
Edited per comment from user 'repeat' (i am not versed on Scheme)
find([First|List], [First, Middle, Last]):-
append(_, [Last], [First|List]),
length(List, Length),
NLength is Length >> 1,
nth0(NLength, [First|List], Middle).
The head of the clause instantiates the First item of the list, then append/3
takes the Last item, length/2
computes the size-1 of the list, >>/2
will divide that size by 2, and nth0/3
will get the Middle item.