Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How display list given range in haskell

How do I write a function that displays a given range in a list in Haskell? Say that I have the function:

dispRange l x y

that when given values:

dispRange [1,2,4,5,6,7] 0 3 

displays all the elements from position 0 to 3, thus the list returned would be:

[1,2,4,5]
like image 387
Ryan Thompson Avatar asked Jul 01 '26 04:07

Ryan Thompson


1 Answers

We can use a combination of drop :: Int -> [a] -> [a] and take :: Int -> [a] -> [a] for this:

For a range i to j, we first drop i elements, and then take j-i+1 elements (since both indices are inclusive, we thus need to add one).

For example:

dispRange :: [a] -> Int -> Int -> [a]
dispRange l i j = take (j-i+1) (drop i l)

We can guard against negative numbers and j being less than i with:

dispRange :: [a] -> Int -> Int -> Maybe [a]
dispRange l i j | i < 0 || j < i = Nothing
                | otherwise = Just (take (j-i+1) (drop i l))
like image 76
Willem Van Onsem Avatar answered Jul 03 '26 02:07

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!