OCaml中的`and`关键字是什么意思?

18

我对OCaml中的and关键字感到困惑。查看此代码后,我发现

type env = {
    (* fields for a local environment described here *)
}

and genv {
    (* fields for a global environment here *)
}

然后稍后,

let rec debug stack env (r, ty) = (* a function definition *)

and debugl stack env x = (* another function definition *)

在这里发生了什么?and关键字只是复制最后一个typeletlet rec语句吗?有没有and rec语句?为什么我要使用and而不仅仅输入lettype,以使我的代码在重构时更加健壮?还有什么其他需要知道的吗?

1个回答

27
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)

(* second version *)

let rec is_even x =
  x = 0 || is_odd (x - 1)
and is_odd x =
  x <> 0 && is_even (x - 1)

您可以在这里找到此示例。

对于相互递归的类型,要找到一个配置比较困难,但是根据维基百科页面,我们可以定义treesforests如下:

 type 'a tree = Empty | Node of 'a * 'a forest
 and 'a forest = Nil | Cons of 'a tree * 'a forest

作为一个例子,由空树、标记为a的单节点树以及带有标记bc的两个节点的树组成的森林将被表示为:
 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 *)
                     )
               )
         );;
  

而 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

而我们得到的是

# size_forest f1;;
- : int = 3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接