Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml: Pattern matching vs If/else statements

So, I'm totally new to OCaml and am moving pretty slowly in getting my first functions implemented. One thing I'm having trouble understanding is when to use pattern matching abilities like

let foo = 
[] -> true
| _  -> false;;

vs using the if else structure like

let foo a = 
if a = [] then true else false;;

When should I use each?

like image 378
Casey Patton Avatar asked Sep 24 '11 02:09

Casey Patton


People also ask

Is pattern matching faster than if else?

Conversation. Python 3.10 match statements are faster at pattern matching sequences than equivalent if-statements. MUCH faster. The second functions runs 86% faster than the first.

How does pattern matching work in OCaml?

Pattern matching comes up in several places in OCaml: as a powerful control structure combining a multi-armed conditional, unification, data destructuring and variable binding; as a shortcut way of defining functions by case analysis; and as a way of handling exceptions.

What does H :: t mean in OCaml?

The pattern h :: t matches any non-empty list, calls the head of the list h (one element, the first one), and the tail of the list t (zero or more elements after the first one). The operator :: is the list constructor (often called "cons"), which is why these patterns match lists.

What is T in OCaml?

Here is an OCaml data type for a binary tree carrying any kind of data: # type 'a tree = | Leaf | Node of 'a tree * 'a * 'a tree;; type 'a tree = Leaf | Node of 'a tree * 'a * 'a tree # let t = Node (Node (Leaf, 1, Leaf), 2, Node (Node (Leaf, 3, Leaf), 4, Leaf));; val t : int tree = Node (Node (Leaf, 1, Leaf), 2, Node ...


1 Answers

I don't think there's a clear cut answer to that question. First, the obvious case of pattern matching is when you need destructing, e.g.:

let rec sum = function
    | [] -> 0
    | head :: tail -> head + sum tail;;

Another obvious case is when you're defining a recursive function, pattern matching make the edge condition clearer, e.g.:

let rec factorial = function
    | 0 -> 1
    | n -> n * factorial(n - 1);;

instead of:

let rec factorial = function n -> 
  if n = 0 then 
    1 
  else
    n * factorial(n-1);;

That might not be a great example, just use your imagination to figure out more complex edge conditions! ;-)

In term of regular (say C like) languages, I could say that you should use pattern matching instead of switch/case and if in place of the ternary operator. For everything else it's kind of a grey zone but pattern matching is usually preferred in the ML family of languages.

like image 158
Nicolas Buduroi Avatar answered Oct 21 '22 18:10

Nicolas Buduroi