and
关键字在IT技术中的用途主要为避免使用多个
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)
let rec is_even x =
x = 0 || is_odd (x - 1)
and is_odd x =
x <> 0 && is_even (x - 1)
您可以在这里找到此示例。
对于相互递归的类型,要找到一个配置比较困难,但是根据维基百科页面,我们可以定义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,
Cons (Node ('a',
Nil),
Cons (Node ('b',
Cons (Node ('c',
Nil),
Nil)
),
Nil
)
)
);;
而 size 函数(计算森林中节点数量)应为:
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
而我们得到的是
- : int = 3