回

02 / 17 · Variables and Functions

let 与函数

函数就是值。类型是推出来的,不用先写签名。

let square x = x * x 是 let square = fun x -> x * x 的糖。多个参数是柯里化:ratio 的类型是 int -> int -> float,不是「一个二元函数」。

x * x 把 x 钉死成 int。Float.of_int 是过桥,OCaml 不会在除法时悄悄把整数变浮点。

例子

utop
let square x = x * x
val square : int -> int = <fun>
square (square 2)
- : int = 16
let ratio x y =
  Float.of_int x /. Float.of_int y
val ratio : int -> int -> float = <fun>
ratio 4 3
- : float = 1.33333333333

改一改

改完再跑

解释器覆盖书前半的核心:函数、标签参数、模式、记录、变体、ref、模块,以及简化的 Map 和 JSON。没有 GADT 细化、Async 和独立编译。

先预测,再对照

1 / 2

square 的类型是?

2 / 2

square (square 2) 的值?