Re: if expression and match expression
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <20151009162922.Horde.SaJ7wOEEdVBFGwYnQ7V3JDe@webmail.in-berlin.de> |
Zitat von "Jeremy Yallop [email protected] [ocaml_beginners]" <[email protected]> (Fri, 9 Oct 2015 15:13:35 +0100) > On 9 October 2015 at 14:56, Hendrik Boom [email protected] > [ocaml_beginners] <[email protected]> wrote: >> 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 >> ;; > > List.tl should usually be avoided, too, since it fails on empty lists. > It's better to use the variable that's bound to the tail of the list > by pattern matching. It's at leastmore elegant. But in the code above, if "List.tl l" would fail, then l would be empty, and that means, that the first pattern would match; and the List.tl would not be called. But calling List.tl here would mean doubled extraction of the value, and therefore be unnecessary computation: the "h::t" already deperated into head and tail, and then List.tl is called *again*, which means this could have been avoided - just reuse the "tl" from the match. Ciao, Oliver