Tutorial by Examples

let rec factorial n = match n with | 0 | 1 -> 1 | n -> n * (factorial (n - 1)) This function matches on both the values 0 and 1 and maps them to the base case of our recursive definition. Then all other numbers map to the recursive call of this function.
We define the type of boolean expressions whose atoms are identified by strings as type expr = | Atom of string | Not of expr | And of expr * expr | Or of expr * expr and can evaluate these expressions using an oracle : string -> bool giving the values of the atoms we find as follows: le...
Pattern matching allows to deconstruct complex values and it is by no way limited to the “outer most” level of the representation of a value. To illustrate this, we implement the function transforming a boolean expression into a boolean expression where all negations are only on atoms, the so calle...
Pattern matching can be used to deconstruct records. We illustrate this with a record type representing locations in a text file, e.g. the source code of a program. type location = { filename : string; line: int; column: int; offset: int; } A value x of type location can be deconstr...
Here we demonstrate how to process lists recursively using OCaml's pattern matching syntax. let rec map f lst = match lst with | [] -> [] | hd::tl -> (f hd)::(map f tl) In this case, the pattern [] matches the empty list, while hd::tl matches any list that has at least one element...
The keyword function can be used to initiate pattern-matching on the the last argument of a function. For example, we can write a function called sum, which computes the sum of a list of integers, this way let rec sum = function | [] -> 0 | h::t -> h + sum t ;; val sum : int list -&...

Page 1 of 1