Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

list

prolog

dcg

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 ?

like image 484
Anonymous Avatar asked Oct 10 '12 18:10

Anonymous


2 Answers

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.

like image 88
Sergey Kalinichenko Avatar answered Sep 20 '22 09:09

Sergey Kalinichenko


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

like image 33
false Avatar answered Sep 23 '22 09:09

false