(* The solution of exercise 3 from the SML handout *)
fun split l =
let
fun splitAt 0 l = ([], l)
| splitAt i (h :: t) =
let val (first, second) = splitAt (i-1) t
in (h :: first, second)
end
in
splitAt (length l div 2) l
end;
fun testSplit f =
f [1, 2, 3, 4, 5, 6] = ([1,2,3],[4,5,6]) andalso
f [1, 2, 3, 4, 5, 6, 7] = ([1,2,3],[4,5,6,7]) andalso
f [1, 2] = ([1],[2]) andalso
f [1] = ([],[1]) andalso
f [] = ([], []);
fun splitAgain l =
let
fun splitWithTwoPointers (h :: t) (_ :: _ :: rest) =
let
val (first, second) = splitWithTwoPointers t rest
in
(h :: first, second)
end
| splitWithTwoPointers l _ = ([], l)
in
splitWithTwoPointers l l
end;