Problem 18

99 Haskell Problems

Problem 18

(**) Extract a slice from a list.

Given two indices, i and k, the slice is the list containing the elements between the i’th and k’th element of the original list (both limits included). Start counting the elements with 1.

Example:

* (slice '(a b c d e f g h i k) 3 7)
(C D E F G)

Example in Haskell:

*Main> slice ['a','b','c','d','e','f','g','h','i','k'] 3 7
"cdefg"

Solution:

slice :: [a] -> Int -> Int -> [a]
slice [] _ _ = []
slice (x:xs) a b
    | a > 1 && b > 0 = slice xs (a-1) (b-1)
    | b > 0 = x:(slice xs 0 (b-1))
    | otherwise = []

This was very similar to the previous problem. I used the input as an indices for counting what to extract out.