Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 422
Jon W Avatar asked Jan 04 '11 19:01

Jon W


People also ask

Can a list be sliced in Python?

In short, slicing is a flexible tool to build new lists out of an existing list. Python supports slice notation for any sequential data type like lists, strings, tuples, bytes, bytearrays, and ranges. Also, any new data structure can add its support as well.

Can a tuple be sliced like a list?

We can use slicing in tuples I'm the same way as we use in strings and lists. Tuple slicing is basically used to obtain a range of items. Furthermore, we perform tuple slicing using the slicing operator.

Is Haskell 0 indexed?

Indexes are zero based, so [1,2,3] !! 0 will result in 1 .


2 Answers

There's no built-in function to slice a list, but you can easily write one yourself using drop and take:

slice :: Int -> Int -> [a] -> [a] slice from to xs = take (to - from + 1) (drop from xs) 

It should be pointed out that since Haskell lists are singly linked lists (while python lists are arrays), creating sublists like that will be O(to), not O(to - from) like in python (assuming of course that the whole list actually gets evaluated - otherwise Haskell's laziness takes effect).

like image 100
sepp2k Avatar answered Oct 16 '22 21:10

sepp2k


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.

like image 41
Thomas M. DuBuisson Avatar answered Oct 16 '22 20:10

Thomas M. DuBuisson