Posted By

rtperson on 08/21/11


Tagged

algorithm problems 99


Versions (?)

Haskell 99 Problems - Number 18 and 19


 / Published in: Haskell
 

URL: http://www.haskell.org/haskellwiki/99_questions/11_to_20

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...)

  1. slice :: [a] -> Int -> Int -> [a]
  2. slice xs i k = ((drop (i-1)) . reverse . (drop end) . reverse) xs
  3. where
  4. end = (length xs - k)
  5.  
  6. -- More efficient solution (from the solutions):
  7.  
  8. slice' xs i k | i>0 = take (k-i+1) $ drop (i-1) xs
  9. -- I forgot all about take when solving this...
  10.  
  11. rotate xs n | n > 0 = (drop n xs) ++ (take n xs)
  12. | n <= 0 = (drop sizeRecip xs) ++ (take sizeRecip xs)
  13. where sizeRecip = (length xs) + n

Report this snippet  

You need to login to post a comment.