Posted By

rtperson on 08/18/11


Tagged

problems 99


Versions (?)

Haskell 99 Problems - Number 17


 / Published in: Haskell
 

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

problem 17, Split a list into two parts; the length of the first part is given. Do not use any predefined predicates. (Meaning no splitAt or take or drop) *Main> split "abcdefghik" 3 ("abc", "defghik")

  1. -- Introducing my convoluted implementation of splitAt
  2. split :: [a] -> Int -> ([a], [a])
  3. split xs n = (pre xs 0 n, post xs 0 (n-1))
  4. where pre :: [a] -> Int -> Int -> [a]
  5. pre [] _ _ = []
  6. pre xs dex n
  7. | dex > length xs = xs
  8. | n > length xs = xs
  9. | otherwise = if (dex < n)
  10. then xs!!dex : pre xs (dex+1) n
  11. else []
  12. post :: [a] -> Int -> Int -> [a]
  13. post [] _ _ = []
  14. post (x:xs) dex n
  15. | n < 0 = (x:xs)
  16. | otherwise = if (dex < n)
  17. then post xs (dex+1) n
  18. else xs
  19.  
  20. -- Or, to borrow from the solutions on Haskell.org
  21. -- (which is incorrectfor negative n, BTW)
  22.  
  23. split' :: [a] -> Int -> ([a], [a])
  24. split' xs 0 = ([], xs)
  25. split' (x:xs) n = let (f,l) = split xs (n-1) in (x : f, l)

Report this snippet  

You need to login to post a comment.