匹配記錄欄位
模式匹配可用於解構記錄。我們用表示文字檔案中位置的記錄型別來說明這一點,例如程式的原始碼。
type location = {
  filename : string;
  line: int;
  column: int;
  offset: int;
}
可以解構型別位置的值 x,如下所示:
let { filename; line; column; offset; } = x
類似的語法可用於定義函式,例如列印位置的函式:
let print_location { filename; line; column; offset; } =
  Printf.printf "%s: %d: %d" filename line column
或者
let print_location = function { filename; line; column; offset; } ->
  Printf.printf "%s: %d: %d" filename line column
匹配記錄的模式不需要提及記錄的所有欄位。由於該函式不使用 offset 欄位,我們可以將其刪除:
let print_location { filename; line; column; } =
  Printf.printf "%s: %d: %d" filename line column
在模組中定義記錄時,足以限定模式中出現的第一個欄位:
module Location =
struct
  type t = {
      filename : string;
      line: int;
      column: int;
      offset: int;
    }
end
let print_location { Location.filename; line; column; } =
  Printf.printf "%s: %d: %d" filename line column