I am trying to find the index position of the minimum element in a list and print the element at the corresponding index position in another list.
For example:
?- min2(X,Y,[a,b,c],[5,3,7]).
X= b
y= 3 Code:
min2(A,B,[A|_],[B|_]).
min2(A,B,[X|T1],[Y|T2]) :- smallest(W,[Y|T2]), % using a predicate to find the min element in teh list
B is W, % setting B to the result of above(i.e the min element)
min2(A,B,T1,T2). % looking up position corresponding to min element in list1 the predicate for finding the min element in the list is:
smallest(Head, [Head]).
smallest(Element, [Head|Tail]) :- smallest(E, Tail), Head =< E, Element is Head.
smallest(Element, [Head|Tail]) :- smallest(E, Tail), E < Head , Element is E. The result I am getting is :
X = a,
Y = 5 ;
X = b,
Y = 3 ;
false. It somehow picks the first element also. My base case could be wrong? I tried altering the base case to min2(A,B,[A|_],[B|_]). and it breaks.
Please show me where I am going wrong.
Thanks.