Inconsistency of scoping between "type ...and " and "let ...and " in Ocaml
I wonder why in OCaml, let ... and
does not have the same kind of scoping as type ... and
.
The following one is OK, t2
is in the same scope as t1
:
# type t1 = t2
and t2 = int;;
This following one is wrong, v2
is not in scope:
# let v1 = v2
and v2 = 3;;
Characters 9-11:
let v1 = v2
^^
Error: Unbound value v2
Even let rec
does not work:
# let rec v1 = v2
and v2 = 3开发者_C百科;;
Characters 13-15:
let rec v1 = v2
^^
Error: This kind of expression is not allowed as right-hand side of `let rec'
Why this inconsistency of scoping between type... and
and let...and
?
Types are implicitly recursive. If you want to have the same effect with "let", use "let rec .. and".
In an ideal language, binding forms where that makes sense should have two versions, one recursive and one non-recursive. That's the case for let
in Caml, you have let
and let rec
. There is no accessible form of non-recursive type binding; it need not be the default, even type nonrec ...
would do. This is a defect of the Caml syntax; bad consequences of the inability of non-recursive type definition are given in this blog post for example.
Regarding your second example, this is not about scoping, but the validity of certain recursive definitions and not others. This is an entirely orthogonal concern (see the ocaml manual for which recursive definitions are valid), and let rec
does exactly what you want here, scoping-wise.
精彩评论