简体   繁体   中英

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 ?

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 -notation:

firstlast(Xs) :-
    phrase(([X],...,[X]), Xs).

... --> [] | [_], ... .

I am not sure whether firstlast([1]) should succeed or not ...

Well since you can only use a recursion with firstlast/1 the solution will look like:

firstlast(...) :- ... .
firstlast(...) :- ... .
firstlast(...) :- ... .
....
firstlast(...) :- ... .

some of those will be the rules regarding the base case and some of them the rules that "eat away" the problem. this problem requires one check: compare the first and the last element. so, in your base case you should have only these 2 elements; you dont need anything else. so the solution will ignore all the other elements

last hint: you can access the 2 first elements of a list with the following unification pattern:

foo([H1,H2|T])

So fair i got this:

firstlast([H,_|T]) :-
(T1 = H, T1 = T) -> firstlast([H|T]).

My code compares the last and first element but the recursion is just wrong :/

As answered above it should not be allowed to succed with one element in the list. Though im only allowed to use the predicate "firstlast".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM