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.

OCaml List rev_map vs map

If you found this page, you are probably very familiar with OCaml already!So, OCaml has a ````map```` function whose purpose is pretty cl...… Continue reading

How to optimize PyTorch code ?

Published on March 17, 2024

Acronyms of deep learning

Published on March 10, 2024