views:

125

answers:

2

I encountered the following construct in various places throughout Ocaml project I'm reading the code of.

match something with
  true -> foo
  | false -> bar

At first glance, it works like usual if statement. At second glance, it.. works like usual if statement! At third glance, I decided to ask at SO. Does this construct have special meaning or a subtle difference from if statement that matters in peculiar cases?

+9  A: 

Yep, it's an if statement.

Often match cases are more common in OCaml code than if, so it may be used for uniformity.

David Crawshaw
I agree but I would put it another way: I think programming in ML makes you see patterns to match everywhere after a while, so that you write "match x with" first and start thinking after that.
Pascal Cuoq
Not only is it equivalent to an if statement, it's quite likely that all if statements get desugared in this way by the compiler.
Chris Conway
+2  A: 

I don't agree with the previous answer, it DOES the work of an if statement but it's more flexible than that.

"pattern matching is a switch statement but 10 times more powerful" someone stated

take a look at this tutorial explaining ways to use pattern matching Link here

Also, when using OCAML pattern matching is the way to allow you break composed data to simple ones, for example a list, tuple and much more

  > Let imply v = 
    match v with 
     | True, x -> x 
     | False, _ -> true;; 

  > Let head = function 
   | [] -> 42 
   | H:: _ -> am;

  > Let rec sum = function 
   | [] -> 0 
   | H:: l -> h + sum l;;
martani_net
Thank you for useful examples and a good reminder for those who learn OCaml. My question, however, was not about using `match` in general, but about a particular use of it, when a boolean value is matched against `true` and `false` only. In such cases it indeed works as `if` operator. David's answer and subsequent comments explain this.
Pavel Shved