1 / 2
12 / 17 · Imperative Programming
ref 与 for
需要状态时,把可变的那一格单独框起来。
ref 0 的类型是 int ref。! 读,:= 写。这和 = 无关,= 是比较。
for 的循环变量是每一轮一个新的 int,不能给 i 赋值。要累加,就累加 ref。循环体的值被丢掉,最后一句 !total 才是函数的结果。
例子
utop
let sum_upto n =
let total = ref 0 in
for i = 1 to n do
total := !total + i
done;
!totalval sum_upto : int -> int = <fun>
sum_upto 10- : int = 55
改一改
改完再跑
解释器覆盖书前半的核心:函数、标签参数、模式、记录、变体、ref、模块,以及简化的 Map 和 JSON。没有 GADT 细化、Async 和独立编译。
先预测,再对照
2 / 2