我对and
OCaml中的关键字感到困惑。查看这段代码,我看到了
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
关键字只是复制过去的type
,let
或let rec
声明?有这样的and rec
说法吗?为什么我要使用and
而不是仅仅输入let
or type
,而使我的代码不那么容易重构?还有什么我应该知道的吗?
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)
(您可以在此处找到此示例)
对于相互递归的类型,很难找到配置,但是在此Wikipedia页面之后,我们将定义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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句