Skip to content

OCaml 速查表

函数优先、兼具命令式与面向对象特性的强类型推断语言。

01

快速上手

Hello World

OCaml 程序以 let () = ... 开头。

ocaml
let () = print_endline "Hello, World!"

let 绑定

let 绑定默认不可变。

ocaml
let x = 10
let y = 20
let () = Printf.printf "%d\n" (x + y)

函数

函数自动柯里化。

ocaml
let add a b = a + b
let () = print_int (add 3 4)

管道

|> 是管道运算符。

ocaml
let result =
  [1; 2; 3; 4; 5]
  |> List.filter (fun x -> x mod 2 = 0)
  |> List.map (fun x -> x * 2)
  |> List.fold_left (+) 0
02

类型

记录

记录是带名字的积类型。

ocaml
type person = { name: string; age: int }
let p = { name = "Alice"; age = 30 }
let () = print_string p.name

变体

变体是和类型;用 function 做模式匹配。

ocaml
type shape =
  | Circle of float
  | Rectangle of float * float

let area = function
  | Circle r -> 3.14 *. r *. r
  | Rectangle (w, h) -> w *. h

Option

Option 类型保证空值安全。

ocaml
let safe_div a b =
  if b = 0 then None else Some (a / b)
03

集合

列表

List 模块提供标准函数式操作。

ocaml
let lst = [1; 2; 3; 4; 5]
let doubled = List.map (fun x -> x * 2) lst
let evens = List.filter (fun x -> x mod 2 = 0) lst
let sum = List.fold_left (+) 0 lst

数组

数组可变;用 .() 索引。

ocaml
let arr = [|1; 2; 3|]
let () = arr.(0) <- 10

这篇内容对您有帮助吗?