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

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

    I had a similar problem and used a list comprehension:

    -- Where lst is an arbitrary list and indc is a list of indices
    
    [lst!!x|x<-[1..]] -- all of lst
    [lst!!x|x<-[1,3..]] -- odd-indexed elements of lst
    [lst!!x|x<-indc]
    

    Perhaps not as tidy as python's slices, but it does the job. Note that indc can be in any order an need not be contiguous.

    As noted, Haskell's use of LINKED lists makes this function O(n) where n is the maximum index accessed as opposed to python's slicing which depends on the number of values accessed.

    Disclaimer: I am still new to Haskell and I welcome any corrections.

提交回复
热议问题