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?
Yep, it's an if statement.
Often match
cases are more common in OCaml code than if
, so it may be used for uniformity.
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;;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With