I am trying to understand deeply nested recursion in OCaml by using the sorting list algorithm. For this reason I am tracing the below code which has a recursive function sort
and calls another function insert
.
let rec sort (lst : int list) = match lst with [] -> [] | head :: tail -> insert head (sort tail)and insert elt lst = match lst with | [] -> [ elt ] | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail
I understand the first recursive calls for sort
, but after that I cannot follow.
For instance, suppose we have the list [6, 2, 5, 3]
. After sorting the tail
of this list as 2,3,5
where in the code the head
6
is compared to each element of this tail? Can somebody provide a hint for the trace results?
utop # sort [6; 2; 5; 3];; > sort <-- [6; 2; 5; 3] > sort <-- [2; 5; 3] > sort <-- [5; 3] > sort <-- [3] > sort <-- [] > sort --> [] > insert <-- 3 > insert --> > insert* <-- [] > insert* --> [3] > sort --> [3] > insert <-- 5 > insert --> > insert* <-- [3] > insert <-- 5 > insert --> > insert* <-- [] > insert* --> [5] > insert* --> [3; 5] > sort --> [3; 5] > insert <-- 2 > insert --> > insert* <-- [3; 5] > insert* --> [2; 3; 5] > sort --> [2; 3; 5] > insert <-- 6 > insert --> > insert* <-- [2; 3; 5] > insert <-- 6 > insert --> > insert* <-- [3; 5] > insert <-- 6 > insert --> > insert* <-- [5] > insert <-- 6 > insert --> > insert* <-- [] > insert* --> [6] > insert* --> [5; 6] > insert* --> [3; 5; 6] > insert* --> [2; 3; 5; 6] > sort --> [2; 3; 5; 6] > > - : int list = [2; 3; 5; 6]**