99 questions/Solutions/17

From HaskellWiki
< 99 questions‎ | Solutions
Revision as of 15:45, 13 July 2010 by Wapcaplet (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

(*) Split a list into two parts; the length of the first part is given.

Do not use any predefined predicates.

Solution using take and drop:

split xs n = (take n xs, drop n xs)

Alternatively, we have the following recursive solution:

split :: [a] -> Int -> ([a], [a])
split []         _             = ([], [])
split l@(x : xs) n | n > 0     = (x : ys, zs)
                   | otherwise = ([], l)
    where (ys,zs) = split xs (n - 1)

The same solution as above written more cleanly:

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

Note that this function, with the parameters in the other order, exists as splitAt.