Alex Rivera | Logout

How do you find all of the subsequences of a list?

Asked 2011-03-21T04:49:23.223
13

I'm trying to learn how to list comprehension and I'm trying to figure out a way to find all the subsequences of a list but i'm not quite sure how one would go about that. Could anyone help me?

Edit
Report

1 Answer

13

Ezra's answer covers all subsequences, but if you just want the continuous sub-sequences, you can use:

import Data.List
continuousSubSeqs = filter (not . null) . concatMap inits . tails

I.e you get

Prelude Data.List> continuousSubSeqs "asdf"
["a","as","asd","asdf","s","sd","sdf","d","df","f"]

The above can be written as a list comprehension as well:

import Data.List
continuousSubSeqs ls = [t | i <- inits ls, t <- tails i, not $ null t]
answered 2011-03-21T12:47:17.793

Your Answer