I’m trying to implement a tail-recursive list-sorting function in OCaml, and I’ve come up with the following code:
let tailrec_merge_sort l =
let split l =
The expression
merge (sort left) (sort right)
is not tail-recursive; it calls both (sort left) and (sort right) recursively while there is remaining work in the call (merge).
I think you can fix it with an extra continuation parameter:
let rec sort l k =
match l with
| [] -> k []
| [a] -> k [a]
| list -> let left, right = split list in sort left (fun leftR -> sort right (fun rightR -> k (merge leftR rightR)))
in sort l (fun x -> x)