Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a sublist in Haskell

Tags:

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?

like image 205
PeterM Avatar asked Dec 16 '11 04:12

PeterM


1 Answers

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.

like image 90
ibid Avatar answered Oct 12 '22 00:10

ibid