I'm currently studying OCaml for a functional programming exam and I'm having some difficulties trying to follow the steps of this recursive function in this exercise. The task is to find the most expensive leaf in a int N-ary tree (a leaf cost is given by the sum of integers on the path to a leaf).
This is the type definition:
type 'a ntree = Ntree of 'a * 'a ntree list
this is an auxiliary function for the exercise
let rec maxpair = function
| [] -> failwith "empty list"
| [(x, y)] -> (x, y)
| (x, y) :: (a, b) :: rest ->
if y > b then maxpair ((x, y) :: rest)
else maxpair ((a, b) :: rest)
and finally here's the final function
let rec leaf_cost = function
| Ntree (x, []) -> (x, x)
| Ntree (x, tlist) ->
let (y, c) = maxpair (List.map leaf_cost tlist)
in
(y, c + x)
This is the solution of the exercise, meaning it works. But I'm having trouble trying to analyze every recursive step in the function, especially because I'm a bit confused about the let (y, c) ... in (y, c + x) declaration.