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?
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.
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.
Indexes are zero based, so [1,2,3] !! 0 will result in 1 .
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With