Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "match ... true -> foo | false -> bar" have special meaning in Ocaml?

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?

like image 534
P Shved Avatar asked Sep 26 '09 12:09

P Shved


2 Answers

Yep, it's an if statement.

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

like image 55
David Crawshaw Avatar answered Oct 13 '22 19:10

David Crawshaw


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;; 
like image 33
0xFF Avatar answered Oct 13 '22 19:10

0xFF