functional-programmingocamlml

Pattern matching functions in OCaml


Can everyone explain to me this piece of code ?

let safe_division n = function
| 0 -> failwith "divide by 0"
| m -> n / m

When I excute safeDiv 3 0 , what is the m and n in this case ?

In general case, when does the function match the first and second pattern ?


Solution

  • When you execute safe_division 3 0, first, 3 is bound to the name n and the right-hand side of the declaration is then evaluated.

    This is a function, so the next argument, 0, is matched against the different cases, in order. Here, it matches the first case, so the right-hand side is evaluated and an exception is thrown. In this case, the name m is never bound to anything.

    If the second argument was, for example, 1, then it would have matched the second case (this case matches every possible value anyway, it's a default case), binding the name m to the value 1 and then returning the result of n / m.