我对andOCaml中的关键字感到困惑.通过这段代码,我看到了
type env = {
(* fields for a local environment described here *)
}
and genv {
(* fields for a global environment here *)
}
Run Code Online (Sandbox Code Playgroud)
再后来,
let rec debug stack env (r, ty) = (* a function definition *)
and debugl stack env x = (* another function definition *)
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?是否and关键字只是复制过去的type,let或let rec声明?是否有and rec声明这样的事情?为什么我要使用and而不是仅仅键入let或type使我的代码不那么脆弱的重构?还有什么我应该知道的吗?
Lho*_*ooq 17
该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
...
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
(你可以在这里找到这个例子)
对于相互递归的类型,找到一个配置比较困难,但是按照我们定义的维基百科页面进行定义trees,forests如下所示
type 'a tree = Empty | Node of 'a * 'a forest
and 'a forest = Nil | Cons of 'a tree * 'a forest
Run Code Online (Sandbox Code Playgroud)
例如,由空树组成的森林,标记为'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 *)
)
)
);;
Run Code Online (Sandbox Code Playgroud)
而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
Run Code Online (Sandbox Code Playgroud)
我们得到了
# size_forest f1;;
- : int = 3
Run Code Online (Sandbox Code Playgroud)