I am using Prolog and I am trying to find a way to implement a predicate in which it takes as arguments two lists and returns a list containing the common elements between them which are found in the same positions in both lists.
The predicate is as follows:
correct_positions(List1, List2,R): succeeds if R is a list containing the letters that occur in both List1 and List2 in the same positions.
Example:
?- correct_positions([h,e,l,l,o],[h,o,r,s,e],R).
R=[h];
false.
The letter "h" in the previous example is found in both lists at the 1st position, so it should be added to R(the result list). Both letters "e" and "o" also occur in both lists, but they do not occur at the same positions so they are not added to the result list.
Another example:
?- correct_positions([o,r,l,l,a],[l,o,r,l,a],R).
R=[l,a];
false.
In the previous example, the letter "l" occurs twice in both lists, but only the occurrence in the 4th position will be added to the result(because it is found in the same positions in both lists) as well as the letter "a" which is found in the 5th position in both lists. (Letters "r" and "o" also occur in the two lists. However, they do not occur at the same positions so they are not added to the result list.
CodePudding user response:
Assuming same length input lists, a possible solution is as follows:
correct_positions([], [], []).
correct_positions([X|A], [X|B], [X|C]) :-
correct_positions(A, B, C).
correct_positions([X|A], [Y|B], C) :-
dif(X, Y),
correct_positions(A, B, C).
Examples:
?- correct_positions([h,e,l,l,o], [h,o,r,s,e], R).
R = [h] ;
false.
?- correct_positions([o,r,l,l,a], [l,o,r,l,a], R).
R = [l, a] ;
false.
?- correct_positions([X,r,l,l,a], [l,o,r,l,a], R).
X = l,
R = [l, l, a] ;
R = [l, a],
dif(X, l) ;
false.
Remark To deal with input lists of different lengths, you need to generalize the base case.
correct_positions([], [], []). % lists of the same length
correct_positions([], [_|_], []). % first list is the shortest
correct_positions([_|_], [], []). % first list is the longest
correct_positions([X|A], [X|B], [X|C]) :-
correct_positions(A, B, C).
correct_positions([X|A], [Y|B], C) :-
dif(X, Y),
correct_positions(A, B, C).