Search code examples
listhaskellsyntax

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?


Solution

  • 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).