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

后端 未结 12 1042
南方客
南方客 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:30

    I've wrote this code that works for negative numbers as well, like Python's list slicing, except for reversing lists, which I find unrelated to list slicing:

    slice :: Int -> Int -> [a] -> [a]
    
    slice 0 x arr
      | x < 0 = slice 0 ((length arr)+(x)) arr
      | x == (length arr) = arr
      | otherwise = slice 0 (x) (init arr)
    
    slice x y arr
      | x < 0 = slice ((length arr)+x) y arr 
      | y < 0 = slice x ((length arr)+y) arr
      | otherwise = slice (x-1) (y-1) (tail arr)
    
    main = do
      print(slice (-3) (-1) [3, 4, 29, 4, 6]) -- [29,4]
      print(slice (2) (-1) [35, 345, 23, 24, 69, 2, 34, 523]) -- [23,24,69,32,34]
      print(slice 2 5 [34, 5, 5, 3, 43, 4, 23] ) -- [5,3,43]
    
    
    

提交回复
热议问题