# 99 questions/Solutions/17

### From HaskellWiki

< 99 questions | Solutions(Difference between revisions)

(cleanup) |
|||

Line 3: | Line 3: | ||

Do not use any predefined predicates. |
Do not use any predefined predicates. |
||

− | Solution using take and drop: |
+ | Solution using <hask>take</hask> and <hask>drop</hask>: |

+ | |||

<haskell> |
<haskell> |
||

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

</haskell> |
</haskell> |
||

− | Alternatively, we have the following recursive solution: |
+ | Or even simpler using <hask>splitAt</hask>: |

+ | |||

+ | <haskell> |
||

+ | split = flip splitAt |
||

+ | </haskell> |
||

+ | |||

+ | But these should clearly be considered "predefined predicates". Alternatively, we have the following recursive solution: |
||

+ | |||

<haskell> |
<haskell> |
||

split :: [a] -> Int -> ([a], [a]) |
split :: [a] -> Int -> ([a], [a]) |
||

Line 18: | Line 18: | ||

The same solution as above written more cleanly: |
The same solution as above written more cleanly: |
||

+ | |||

<haskell> |
<haskell> |
||

split :: [a] -> Int -> ([a], [a]) |
split :: [a] -> Int -> ([a], [a]) |
||

Line 23: | Line 24: | ||

split (x:xs) n = let (f,l) = split xs (n-1) in (x : f, l) |
split (x:xs) n = let (f,l) = split xs (n-1) in (x : f, l) |
||

</haskell> |
</haskell> |
||

− | |||

− | Note that this function, with the parameters in the other order, exists as <hask>splitAt</hask>. |

## Revision as of 20:13, 15 July 2010

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

Do not use any predefined predicates.

Solution usingtake

drop

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

splitAt

split = flip splitAt

But these should clearly be considered "predefined predicates". 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)