What this code mean in ocaml

Hi,
i have this function avec (exn -> bool) that convert exception of type exn to bool . the problem is that i dont understand how its works and use change it.
function Not_found -> true | _ -> false

thank you

The function keyword in OCaml is syntactic sugar for (fun x -> match x with ...), essentially it simplifies defining some functions by immediately matching on the input.

Your example could also be written

(fun x -> 
  match x with
   | Not_found -> true
   | _ -> false)

This function can be called just like any other OCaml function. Here are two short examples:

(function Not_found -> true | _ -> false) Not_found;;   (* evaluates to true *)
(function Not_found -> true | _ -> false) (Invalid_argument "Invalid arg exn");;   (* evaluates to false *)

You can also bind this function to a variable and use it that way.

let is_not_found = function 
  | Not_found -> true
  | _ -> false;;

This function can now be used in the rest of your program.

is_not_found Not_found;;   (* evaluates to true *)
is_not_found (Invalid_argument "Invalid arg exn");;   (* evaluates to false *)
1 Like