Use mem and then find or use find and handle the exception?

Suppose I want to write a function that tries to find a key on a map and returns Noneif it cannot: try_find: 'a -> ('a, 'b) Map.t -> 'b optionwhat is the canonical way to do this? To first check if key c exists mem, then call find? Or catch an exception Not_found? The batteries seem to be doing the latter.

On the other hand, in languages ​​such as C # or Java people, it is generally not recommended to use exceptions in such cases for performance reasons. Does Ocaml use exceptions on “normal” execution paths or is it also discouraging?

+4
source share
2 answers

OCaml exceptions run as fast as function calls for the default backend. For Javascript databases, this is not always the case. The canonical way of OCaml is to implement a function that does not throw an exception - use the throwing function and throw the exception in the null variant, for example,

let try_find x xs = try Some (List.find x xs) with Not_found -> None

The call memand findis a performance loss, as you will name the list twice.

. List.find , . , try_find , - (None , ). , . . ( ), , / GADT.

"" Ocaml ?

, OCaml . , . , , Javascript, Java .Net. , . , , , ., result. Janestreet Core ( ), .

( ). . , , , , .

+3

, , OCaml , , , , , .

, . .

, , . , Not_found , . .

+3

Source: https://habr.com/ru/post/1660965/


All Articles