[Haskell-cafe] How to get subset of a list?

Bernie Pope bjpop at csse.unimelb.edu.au
Thu Nov 30 22:28:06 EST 2006


On 01/12/2006, at 12:47 PM, Huazhi (Hank) Gong wrote:

>
> Like given a string list s="This is the string I want to test", I  
> want to get
> the substring. In ruby or other language, it's simple like s 
> [2..10], but how
> to do it in Haskell?


If your indices are in ascending order, and unique, then something  
like this might
do the trick:

    els1 indexes list
       = els' (zip [0..] list) indexes
       where
       els' [] _ = []
       els' _ [] = []
       els' ((j,x):xs) indexes@(i:is)
          | i == j          = x : els' xs is
          | otherwise = els' xs indexes

Of course this is a right fold, so you ought to be able to use foldr.

Here's an attempt:

    els2 indexes list
       = foldr comb undefined [0..] list indexes
       where
       comb _ _ [] _ = []
       comb _ _ _ [] = []
       comb j rec (x:xs) indexes@(i:is)
          | j == i          = x : rec xs is
          | otherwise = rec xs indexes

Bonus marks for figuring out why I used "undefined".

Warning: this is largely untested code.

Cheers,
Bernie.


More information about the Haskell-Cafe mailing list