PeterM
PeterM

Reputation: 2614

Get a sublist in Haskell

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?

Upvotes: 24

Views: 23200

Answers (4)

Nomics
Nomics

Reputation: 716

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

[5,6,7,8,9]

Upvotes: 7

Landei
Landei

Reputation: 54584

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

Upvotes: 1

Dan Burton
Dan Burton

Reputation: 53675

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.

Upvotes: 10

ibid
ibid

Reputation: 3902

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.

Upvotes: 40

Related Questions