and 关键字用于避免多个 let(第一个示例,我从不使用它,但为什么不使用它)或用于类型、函数、模块的相互递归定义...
正如您在第二个示例中看到的那样:
let rec debug stack env (r, ty) =
...
| Tunresolved tyl -> o "intersect("; debugl stack env tyl; o ")"
...
and debugl stack env x =
...
| [x] -> debug stack env x
...
debug 调用debugl,反之亦然。所以and 允许这样做。
[编辑] 没有给出一个合适的例子让我很困扰,所以这里有一个你经常会看到的例子:
let rec is_even x =
if x = 0 then true else is_odd (x - 1)
and is_odd x =
if x = 0 then false else is_even (x - 1)
(你可以找到这个例子here)
对于相互递归的类型,很难找到配置,但遵循 this wikipedia page 我们将定义 trees 和 forests 如下
type 'a tree = Empty | Node of 'a * 'a forest
and 'a forest = Nil | Cons of 'a tree * 'a forest
例如,由空树、标记为a 的单例树和标记为b 和c 的两节点树组成的森林将表示为:
let f1 = Cons (Empty, (* Empty tree *)
Cons (Node ('a', (* Singleton tree *)
Nil), (* End of the first tree *)
Cons (Node ('b', (* Tree composed by 'b'... *)
Cons (Node ('c', (* and 'c' *)
Nil),
Nil)
),
Nil (* End ot the second tree *)
)
)
);;
大小函数(计算森林中的节点数)将是:
let rec size_tree = function
| Empty -> 0
| Node (_, f) -> 1 + size_forest f
and size_forest = function
| Nil -> 0
| Cons (t, f) -> size_tree t + size_forest f
我们得到
# size_forest f1;;
- : int = 3