Get a sublist in Haskell

丶灬走出姿态 提交于 2020-01-01 07:34:49

问题


Probably an easy one, but I've looked through the docs and googled for examples and I'm still not sure of the answer.

If I have a list like this:

[1,2,3,4,5,6,7,8,9,0]

and I want to extract a slice, say from index 4 to index 8 i.e. I want:

[5,6,7,8,9]

What is the idiomatic way to do this in Haskell?


回答1:


First of all, that's not an array, it's a list. I'm not being (merely) pedantic, as arrays are much more problematic in Haskell than lists.

That said, one common way is to use take and drop together:

Prelude> drop 4 . take 9 $ [1,2,3,4,5,6,7,8,9,0]
[5,6,7,8,9]
Prelude> take (9-4) . drop 4 $ [1,2,3,4,5,6,7,8,9,0]
[5,6,7,8,9]

The latter is a bit more efficient.




回答2:


You may be interested in Data.Vector (slice).

ghci> import Data.Vector
ghci> let v = fromList [1..10]
ghci> v
fromList [1,2,3,4,5,6,7,8,9,10]
ghci> slice 4 5 v
fromList [5,6,7,8,9]

Note that slice in Data.Vector takes as inputs the beginning index and the length of the slice.




回答3:


> drop 4 (take 9 [1,2,3,4,5,6,7,8,9,0])

[5,6,7,8,9]



回答4:


Hmmm, not very practical, but maybe it can be improved?

(\(x,y) -> if 4 <= y && y <= 9 then [x] else []) =<< zip [1,2,3,4,5,6,7,8,9] [0..]


来源:https://stackoverflow.com/questions/8529814/get-a-sublist-in-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!