Search code examples
listprologdcg

Prolog List. Check if first and last element in list is similar


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 ?


Solution

  • 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.