Efficient implementation of List.split

Here’s my solution, time and space both in O(n):

let split_list n l =
  let[@tail_mod_cons] rec aux r n = function
    | [] -> []
    | x :: xs as l -> if n > 0 then x :: aux r (n-1) xs else (r := l; [])
  in
  let r = ref [] in
  let u = aux r n l in
  u, !r

Cheers,
Nicolas

2 Likes