OCaml – is it operation is efficient?

If I were asked to improve the efficiency of a function definition let f h acc = (h :: List.hd acc) :: List.tl acc without any other background, I would say it is already enough efficient.

Still, I prefer using pattern matching instead of List.hd and List.tl. It is safer (you naturally find the case acc = [] must be handled specially), and slightly faster than the two function calls:

let f h = function
  | [] -> invalid_arg "empty list"
  | xs::xss -> (h::xs) :: xss

Leave a Comment