Alex Rivera | Logout

Does Haskell have List Slices (i.e. Python)?

Asked 2011-01-04T19:59:07.010
55

Does Haskell have similar syntactic sugar to Python List Slices?

For instance in Python:

x = ['a','b','c','d']
x[1:3] 

gives the characters from index 1 to index 2 included (or to index 3 excluded):

['b','c']

I know Haskell has the (!!) function for specific indices, but is there an equivalent "slicing" or list range function?

Edit
Report

3 Answers

36

If you are trying to match Python "lists" (which isn't a list, as others note) then you might want to use the Haskell vector package which does have a built in slice. Also, Vector can be evaluated in parallel, which I think is really cool.

answered 2011-01-04T20:47:07.187
19

No syntactic sugar. In cases where it's needed, you can just take and drop.

take 2 $ drop 1 $ "abcd" -- gives "bc"
answered 2011-01-04T20:04:43.700
0

Obviously my foldl version loses against the take-drop approach, but maybe someone sees a way to improve it?

slice from to = reverse.snd.foldl build ((from, to + 1), []) where
   build res@((_, 0), _) _ = res  
   build ((0, to), xs) x = ((0, to - 1), x:xs)  
   build ((from, to), xs) _ = ((from - 1, to - 1), xs)
answered 2011-01-05T10:42:59.653

Your Answer