2
votes

Trying to write Prolog rules that incorporates the following rules for a function matchFirstTwo(List1, List2), that evaluates to true if the last two elements of the first list = the first two elements of the second list. Append and reverse cannot be implemented into the solution.

last([X], X).
last([_|Z], X) :- last(Z, X).

nextToLast([X,_], X).
nextToLast([_|Z], X) :- nextToLast(Z, X).

Write matchFirstTwo(List1, List2) — succeeds exactly when List2's first and second elements equal List1's last two elements

% Example :
?- matchFirstTwo([a,b,c,d],[d,c,a,b]).
   true.
2
What about matchFirstTwo([a],[a])?false
It says List2's first and second element are equals btw use recursion and when you reach length of 2 then simply compare themLuai Ghunim
@TomasBy: By editing, you are blocking other edits since reviewing takes so much time. Rather aquire 2k before editing posts!false

2 Answers

2
votes

Here's how we can define matchFirstTwo/2 using widely-available list predicates:

matchFirstTwo(List1, List2) :-
   append([X,Y], _, List2),      % List2's first and second elements
   append(_, [Y,X], List1).      % equal List1's last two elements

Or, more compactly:

matchFirstTwo(List1, [Y,X|_]) :-
   append(_, [X,Y], List1).

Or, even better:

matchFirstTwo(List1, [Y,X|_]) :-
   reverse(List1, [Y,X|_]).

Sample query:

?- matchFirstTwo([a,b,c,d], [d,c,a,b]).
true                                     % succeeds deterministically
1
votes

Keep removing the head of the first list and at the same time decrement length , if you have length of 2 then simply check for the solution.

Without append/3 and reverse/2

matchFirstTwo(List1,List2):-
        length(List1,X),
        match(List1,X,List2).

match(List1,2,List2):-
    compare(List1,List2),!.

match([_|T],Len,List2):-
    NewLength is Len - 1,
    match(T,NewLength,List2).

compare([H1,H2|_],[H1,H2|_]).

You example query has a mistake, As you are trying to compare last two elements of first list with first two elements of second list. so second list must have [c,d,a,b] in-order to get true.