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

后端 未结 12 1045
南方客
南方客 2020-12-05 02:15

Does Haskell have similar syntactic sugar to Python List Slices?

For instance in Python:

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

give

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 02:48

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

提交回复
热议问题