Given a list like:
let list = [1,2,3,4,5,6,7,8,9,10]
I am trying to come up with a way to detect if 7,8,9 exists in the list in sequential order and simply printout ‘success’ if it does and ‘fail’ otherwise.
I am trying to accomplish this using zip for the index. Can someone advise if I am on the right track or if there is a better way to accomplish this?
zip [0..] list
And then something like:
[if (snd x)==
7 && let index = (fst x)
&& (snd x)==8 && (fst x)==(index+1)
&& (snd x)==9 && (fst x)==(index+2)
then "success"
else "fail" | x <- list]
When trying to figure out a list algorithm it’s usually best to start by
thinking about the special case in the list head. In this case, how would you
test that the list begins with
[7,8,9]?I.e. we can just pattern match to the first three elements. Now to generalize
this, if we don’t find the subsequence in the list head, we recursively check
the tail of the list
Now if we want to further generalize this to find any subsequence, we can use
the
isPrefixOffunction fromData.List:We can tidy this up by using
anyandtailsto check if any successivelyshorter tail of the list begins with the given subsequence:
Or, we can simply use the standard library function
isInfixOf. 😉