I got a problem with this
I want to make a list of target position like if I type
?- extractIndices([5,6,7,8,9,5,6],6,List).
it should return
List = [1,6]
which gives all position of 6 in that list.
I wrote code like this:
extractIndices(List , Item, [Index | Indecis]) :-
indexOf(List , Item, Index).
indexOf([Item | _], Item, 0).
indexOf([_ |Tail], Item, Index):-
indexOf(Tail, Item, Index1),
Index is Index1+1.
and this gives me
?- extractIndices([5,6,7,8,9,5,6],6,L).
L = [1|_G2870] ;
L = [6|_G2870] ;
false.
It will be so thankful if someone can help me fix this…
Thank you.
You have provided two rules for
indexOf, one which handles the head of the list, ignoring the tail, and one which handles the tail, ignoring the head. This results in two different solutions to your query as shown.The predicate
nth0can be used to map positions to items in a list.The easiest way to use it is going to be with
findall:You can also make your own solution using something like
indexOf. But you probably want to provide two different rules: one for the base case (usually an empty list), and one recursive case which solves it for the head, and then callsindexOfagain on the tail.