1 / 2
08 / 17 · A Guided Tour
没有的值写成 None
找不到不是异常。option 逼你在类型里把「没有」写出来。
Some 和 None 是普通变体。find 的类型是 'a -> 'a list -> 'a option:调用者必须 match,不能假装一定有值。
Base 里 List.hd 返回 option,不是抛异常。Option.map 遇到 None 就保持 None,不会去调用函数。
例子
utop
let rec find x xs =
match xs with
| [] -> None
| hd :: tl -> if hd = x then Some hd else find x tlval find : 'a -> 'a list -> 'a option = <fun>
find 3 [1; 2; 3]- : int option = Some 3
find 9 [1; 2; 3]- : 'a option = None
Option.map ~f:(fun n -> n * 10) (find 3 [1; 2; 3])- : int option = Some 30
改一改
改完再跑
解释器覆盖书前半的核心:函数、标签参数、模式、记录、变体、ref、模块,以及简化的 Map 和 JSON。没有 GADT 细化、Async 和独立编译。
先预测,再对照
2 / 2