Reputation: 539
I am trying to write a predicate that follows some simple conditions. It should take 2 lists and 2 variables and should return true if the first variable is located at the same position in the first list as the second variable is located in the second list. I did one part but I am struggling to get the other part working. This is what I have done so far, but in some way I need to check the rest of the positions in the list.
position([A|_],[B|_],Var1,Var2):-
A = Var1,
B = Var2.
I want for example to be able to write like this:
position([x,y,z],[1,2,3],z,3).
true .
Thanks in advance.
EDIT
I have tried and what I write keep giving me false, I thought this would work but it doesn't...:
position([A|C],[B|D],Var1,Var2):-
A = Var1,
B = Var2,
position(C,D,Var1,Var2).
Not sure why this doesn't work..
Upvotes: 2
Views: 1317
Reputation: 18683
You need two clauses, one implementing the base case for when you find the variables in the same position and a clause implementing the recursive clause that you use to walk the list until either you found what you're looking for or reach the end of the lists. You're almost there:
position([Head1| _], [Head2| _], Var1, Var2) :-
Head1 == Var1,
Head2 == Var2.
position([_| Tail1], [_| Tail2], Var1, Var2) :-
position(Tail1, Tail2, Var1, Var2).
Note that you may need to use equality, (==)/2
, as above instead of unification, (=)/2
, as two variables always unify. But the choice depends on the possible inputs to your predicate and the exact desired semantics. Also, there can be several solutions. If you're interested in just one, you can add a cut to the end of the first clause or, in alternative, you can use a single clause with an if-then-else control construct:
position([Head1| Tail1], [Head2| Tail2], Var1, Var2) :-
( Head1 == Var1,
Head2 == Var2 ->
true
; position(Tail1, Tail2, Var1, Var2)
).
Upvotes: 0