Return to Snippet

Revision: 50344
at August 18, 2011 06:50 by rtperson


Initial Code
-- Introducing my convoluted implementation of splitAt
split :: [a] -> Int -> ([a], [a])
split xs n = (pre xs 0 n, post xs 0 (n-1))
    where pre :: [a] -> Int -> Int -> [a]
          pre [] _ _ = []
          pre xs dex n
                | dex > length xs = xs
                | n > length xs = xs
                | otherwise = if (dex < n) 
                                    then xs!!dex : pre xs (dex+1) n
                                    else [] 
          post :: [a] -> Int -> Int -> [a]
          post [] _ _ = []
          post (x:xs) dex n
                | n < 0 = (x:xs)
                | otherwise = if (dex < n)
                                then post xs (dex+1) n
                                else xs
                                
-- Or, to borrow from the solutions on Haskell.org 
-- (which is incorrectfor negative n, BTW)

split' :: [a] -> Int -> ([a], [a])
split' xs 0 = ([], xs)
split' (x:xs) n = let (f,l) = split xs (n-1) in (x : f, l)

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

Initial Description
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")

Initial Title
Haskell 99 Problems - Number 17

Initial Tags

                                

Initial Language
Haskell