Example:
firstlast([1,2,3,4,1]).
true;
firstlast([1,2,3,4]).
false;
firstlast([5,10,4,3]).
false;
exc...
The problem is im only allowed to use recursion with the predicate "firstlast". ? I have really tried to break this, but i cant seem to check / compare the last element with the first.
Any hints ?
UPDATE : Since you are not allowed to use other predicates, try this:
firstlast([H,H]).
firstlast([F,_|T]) :- firstlast([F|T]).
The first predicate deals with the base case, the second one removes the second element in a list of three or more items, and recurses down.
You probably mean that the first and last element are the same. Here is a solution using dcg-notation:
firstlast(Xs) :- phrase(([X],...,[X]), Xs). ... --> [] | [_], ... .
I am not sure whether firstlast([1])
should succeed or not ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With