I'm looking to search in a sublist for a particular string. There is a list of strings (possibly duplicates); I have some Item; and I have an Index pointing to the current item required; and I want to search from the index to the end of the list and know if Item is still in there.
The most similar thing I found here was at Prolog: Create sublist, given two indices but I don't need 2 indices and I feel like it shouldn't be that complicated; this also looked close but I didn't really make sense of it Create a sublist from a list given an index and a number of elements. Prolog. I also don't think sublist/3 will do it (plus it looks like it's deprecated based on this - http://www.swi-prolog.org/pldoc/man?predicate=sublist/3 )
E.g., a list [Blue, Orange, Red, Yellow, Orange], a sequenceIndex(2), an item of 'Orange' and I want to know that Orange is in the sublist [Red, Yellow, Orange].
So, something like this, only this isn't how to use nth I guess:
sequenceIndex(0).
sequence([blue, orange, red, yellow, orange]).
stillThere(Color) :-
sequenceIndex(Index),
sequence(Listcolors),
nth(Index, Listcolors, Color).
stillThere(Color) :-
sequenceIndex(Index),
N is Index+1,
sequence(Listcolors),
nth(N, Listcolors, Color).
and I'd call it with have(X), stillThere(X)
, where X
is blue
(etc. it'll change throughout the program).
Many thanks!
You seem to start with 0, so your definition would be
list_index_item(Xs, I, Item) :-
nth0(J, Xs, Item),
J >= I.
?- list_index_item([blue, orange, red, yellow, orange], 2, orange).
true.
?- list_index_item([blue, orange, red, yellow, orange], 2,blue).
false.
This shows a bit the generality of Prolog predicates. The goal nth0(J, Xs, Item)
succeeds for all possible positions, but we are only interested in those that start at I
.