回

06 / 17 · Lists and Patterns

List 模块,而不是手写递归

map、filter、fold 是同一条链表的三种看法。

Base 把函数参数标成 ~f,列表本身是不带标签的那个参数,所以 ~f 可以写在列表前面或后面。

fold 的 ~init 是起点,~f 吃「累积值」和「当前元素」。先写对参数顺序,再谈尾递归。

例子

utop
let nums = [1; 2; 3; 4; 5]
val nums : int list = [1; 2; 3; 4; 5]
List.filter ~f:(fun x -> x mod 2 = 0) nums
- : int list = [2; 4]
List.fold ~init:0 ~f:(fun acc x -> acc + x) nums
- : int = 15
List.map ~f:(fun x -> x * x) nums
- : int list = [1; 4; 9; 16; 25]

改一改

改完再跑

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

先预测,再对照

1 / 2

fold ~init:0,把 [1; 2; 3; 4] 加起来,是多少?

2 / 2

List.map ~f:square [1; 2] 和 List.map [1; 2] ~f:square

在书里读 Lists and Patterns