splitAt

Filed under: haskell

Today I found out that haskell comes with a feature for splitting lists. It comes in the base package (link)

splitAt :: Int -> [a] -> ([a], [a])

The description says:

splitAt n xs returns a tuple where first element is xs prefix of length n and second element is the remainder of the list:

It is equivalent to (take n xs, drop n xs) when n is not _|_ (splitAt _|_ xs = _|_). splitAt is an instance of the more general genericSplitAt, in which n may be of any integral type.

Here are some examples:

splitAt 6 "Hello World!" == ("Hello ","World!")
splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
splitAt 1 [1,2,3] == ([1],[2,3])
splitAt 3 [1,2,3] == ([1,2,3],[])
splitAt 4 [1,2,3] == ([1,2,3],[])
splitAt 0 [1,2,3] == ([],[1,2,3])
splitAt (-1) [1,2,3] == ([],[1,2,3])

Knowing this, now I can set up my mergeSort

let n = length fileInput
let halfway = n `div` 2
let (a,b) = splitAt halfway fileInput