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]
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With