Re: if expression and match expression
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <[email protected]> |
On Thu, Oct 08, 2015 at 08:12:48PM -0700, [email protected] [ocaml_beginners] wrote: > Code first: > > > let rec has_element1 l e = > match l with > | [] -> false > | h::t -> if e = h then true else false > ;; > > let rec has_element2 l e = > match l with > | [] -> false > | h::t -> match h with > | e -> true > | _ -> has_element2 (List.tl l) e > ;; > > > > has_element1 works as I expected. > > And I rewrite has_element1 with replacing 'if expressing' with 'match. > > But has_element2 always return 'true' and it gives me warning: 'Warning 11: this match case is unused' > > > Questions: > > (1) Why does my has_element2 always return true? Match expression I > used in has_element2 not the same as if expression in has_element1? How is the poor compiler to know whether the last alternative belongs with the first or the second match? Try inserting ( before the second match keyword and putting its ")" where it belongs. I think this may be a language design problem. But the problem ends up being caught in the type analysis, so it's probably only confusing. When OCaml misbehaves I usually find it enlightening to be explicit about types and parentheses. -- hendrik