Re: if expression and match expression
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <[email protected]> |
On Fri, Oct 09, 2015 at 03:03:47PM +0200, Gabriel Scherer [email protected] [ocaml_beginners] wrote: > I personally dis-trust "when" guards (which is why I didn't include > them in my reply). I have seen people over-use them and get clever > bugs because of it (a bit of the same way you were surprised with your > simpler bug), and they also prevent the compiler from being able to > tell whether a pattern-matching is exhaustive or has superfluous cases > -- because it does not try to guess the meaning of the boolean test. I > would use an if-then-else in your situation. That said, it is a matter > of taste, and many people will like your code as well. > > Another thing I am sensitive to is that having "_" at the toplevel of > a pattern is bad form in my book. It does not matter much for > algebraic types that are known to have two cases (lists and options), > but whenever you are pattern-matching on a type that *you* defined and > that may get new constructors in the future, using "_" as a pattern > will prevent the compiler from warning you that this pattern-matching > need to be adapted (because it is not exhaustive anymore). Thus I try > to take the habit never to use "_" as a whole pattern (it is often fine > under a constructor), at any type (otherwise it's easy to slip back). > The version with "if" doesn't have a "_" as head pattern, so it is better > in that respect as well. So you'd recommend something like let rec has_element2 l e = match l with | [] -> false | h::t -> h = e or has_element2 (List.tl l) e ;; -- hendrik