Finding the index of the largest element in a list in OCaml

Reading time ~1 minute

As far as I know, there is no implementation of argmax and argmin in the default ocaml library (or perhaps they could be called maxi for more consistency with respect to mapi). The following snippet solves it!

let argmax l =
  let rec aux max_index index max_value = function
    | [] -> max_index
    | h::t -> if h > max_value then aux index (index + 1) h t 
                         else aux max_index (index + 1) max_value t
  in 

  match l with 
  | [] -> 0
  | _ ->   aux 0 0 (List.hd l) l

Note that the defaut behavior with an empty list is to return 0 but it can be changed.

Best books on Fermat's last theorem

I haven't published many articles these days, the main reason being that I got attracted into the history of Fermat's last theorem. This ...… Continue reading

Random number generation in Cython

Published on February 25, 2022