Re: if expression and match expression

"Sébastien Dailly [email protected] [ocaml_beginners]" <[email protected]>
Newsgroups gmane.comp.lang.ocaml.beginners
Message-ID <[email protected]>
Le 2015-10-09 05:55, Seung-jin Kim [email protected] 
[ocaml_beginners] a écrit :
> First of all,
> There was a typo in my very initial question.
> my has_element1 should be
> 
> let rec has_element1 l e =
> match l with
> | [] -> false
> | h::t -> if e = h then true else has_element1 t e;;
> 
> Anyway,, Seems everyone got my point. :-) First time to post this
> group and very new to ocaml.
> 
> I did with ( ) for my second match.
> 
> utop[91]> let rec has_element2 l e =
> match l with
> | [] -> false
> | h::t -> ( match h with
> | e -> true
> | _ -> has_element2 t e
> )
> ;;
> 
> val has_element2 : 'a list -> 'b -> bool = <fun>
> Characters 107-108:
> Warning 11: this match case is unused.
> utop[92]> has_element2 [2;3;4] 10;;
> - : bool = true
> utop[93]>
> 
> Still getting the same warning message with the same result.

Hello,

when you write

> match l with
> | [] -> false
> | h::t -> …

You do not match l with an existing variables named h and t. You create 
two new ones which match the pattern.

The same applies when you write :

> match h with
> | e -> true

You create a new variable name « e » which override the existing 
variable. Of course this pattern always match.

You can write :

- either an if / else structure as in your first example.
- either a gard pattern in your pattern matching.

Regards
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.