vendredi 5 mars 2021

Which is better in OCaml pattern matching, `when` or `if-then-else`?

Let's say we have a type called d:

type d = D of int * int

And we want to do some pattern matching over it, is it better to do it this way:

let dcmp = function 
  | D (x, y) when x > y -> 1 
  | D (x, y) when x < y -> -1
  | _ -> 0

or

let dcmp = function 
  | D (x, y) -> 
    if x > y then 1 else if x < y then -1 else 0

Just in general is better to match patterns with many "when" cases or to match one pattern and the put an "if-then-else" in it?

And where can I get more information about such matters, like good practices in OCaml and syntactic sugars and such?

Aucun commentaire:

Enregistrer un commentaire