Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

Slice a list in haskell with specific indexes

I have this list:

[[0,4,1,4],[1,12,1,4],[2,8,1,4],[3,54,2,4],[4,1,2,2]]

I also have another list: [2,3] -- Represents the indexes i want to get from each sublist

Output should be like:

[[1,4],[1,4],[1,4],[2,4],[2,2]]

Another example:

List :

[[0,4,1,4],[1,12,1,4],[2,8,1,4],[3,54,2,4],[4,1,2,2]]

Indexes : [0,2,3]

Output should be like:

[[0,1,4],[1,1,4],[2,1,4],[3,2,4],[4,2,2]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You obtain the item in a list with a given index with (!!) :: [a] -> Int -> a, for example:

Prelude> [0,4,1,4] !! 0
0
Prelude> [0,4,1,4] !! 2
1
Prelude> [0,4,1,4] !! 3
4

We thus can perform a mapping to obtain the items for a list of items:

Prelude> map ([0,4,1,4] !!) [0,2,3]
[0,1,4]

we thus can slice a list of lists with:

slices :: [Int] -> [[a]] -> [[a]]
slices is = map ((`map` is) . (!!))

For example:

Prelude> slices [0,2,3] [[0,4,1,4],[1,12,1,4],[2,8,1,4],[3,54,2,4],[4,1,2,2]]
[[0,1,4],[1,1,4],[2,1,4],[3,2,4],[4,2,2]]

Using (!!) is however unsafe: it is not guaranteed that a list has an element with the given index, furthermore, it is not very efficient: it takes O(k) to obtain the k-th element. Therefore it is better to work with Vector or an Array and with lookups that return a Nothing when the index is out of range, for example for a Vector, we can use (!?) :: Vector a -> Int -> Maybe a.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...