Posted By

rtperson on 08/21/11

Haskell 99 Problems - Number 18 and 19

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:

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

9 Problem 19 - Rotate a list N places to the left.

``````*Main> rotate ['a','b','c','d','e','f','g','h'] 3
"defghabc"

*Main> rotate ['a','b','c','d','e','f','g','h'] (-2)
"ghabcdef"
``````

(This one is so easy it feels like cheating...)

`slice :: [a] -> Int -> Int -> [a]slice xs i k = ((drop (i-1)) . reverse . (drop end) . reverse) xs  where    end = (length xs - k) -- More efficient solution (from the solutions): slice' xs i k | i>0 = take (k-i+1) \$ drop (i-1) xs -- I forgot all about take when solving this... rotate xs n | n > 0 = (drop n xs) ++ (take n xs)            | n <= 0 = (drop sizeRecip  xs) ++ (take sizeRecip xs)               where sizeRecip = (length xs) + n`