回

05 / 17 · Lists and Patterns

用模式把列表拆开

destutter 是书里的例子:去掉相邻重复。

function 就是 fun x -> match x with 的糖。三条模式要盖住空列表、单元素、以及至少两个元素。最后一条用 hd :: hd2 :: tl,而不是写死长度。

相等就丢掉左边那个,留下 hd2 继续看。不相等就把 hd 接到递归结果前面。顺序写反,重复就去不掉。

例子

utop
let rec destutter = function
  | [] -> []
  | [hd] -> [hd]
  | hd :: hd2 :: tl ->
    if hd = hd2 then destutter (hd2 :: tl)
    else hd :: destutter (hd2 :: tl)
val destutter : 'a list -> 'a list = <fun>
destutter ["hey"; "hey"; "hey"; "man!"]
- : string list = ["hey"; "man!"]

改一改

改完再跑

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

先预测,再对照

1 / 2

destutter ["a"; "a"; "b"; "b"] 得到?

2 / 2

如果删掉 | [] -> [] 这一支,空列表会怎样?

在书里读 Lists and Patterns