Re: if expression and match expression
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <20151009163226.Horde.4c6TvqSbBaKGZTw4MuMrjze@webmail.in-berlin.de> |
Zitat von "Oliver Bandel [email protected] [ocaml_beginners]" <[email protected]> (Fri, 09 Oct 2015 16:29:22 +0200) > 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. typo: I meant: - just reuse the "t" from the match. (I also prefer "hd" and "tl" over "h" and "t" ...) Ciao, Oliver