Explicit var type in OCaml
If I have a type t
type t = C of string;;
And want to explicitly define a开发者_如何学编程 type of the variable to be type t:
let b : t = C 'MyString';;
Can I do it in OCaml?
You don't need to be explicit
let b = C mystring
let b = C "a string litteral"
You can be explicit, but it dy oesn't add anything
let b : t = C foo
The preferred way in general is to use type inference without annotating types, and only be explicit about the type of the identifiers exported to other modules, through the associated .mli
interface file.
In this case, a type annotation doesn't add anything as the C
constructor already is a kind of tag/annotation : C something
is necessarily of type t
, there is no possible confusion.
You can, using either that syntax, or the alternate one:
let b = (C foo : t)
Adding type constraints in this fashion does not usually serve any purpose in a well-formed program, because the type inference algorithm can handle all of it correctly on its own. There are a few exceptions (mostly involving the object-oriented side), but they're quite rare.
Such annotations are mostly useful when a type error happens and you need to understand why a certain expression has a certain type when you expected it to have another, because you can type-annotate intermediate values to have the type error move up through your source code.
Note that there's another way of annotating types, which is to define a signature for your modules. In your example above, your module body would contain:
let b = C foo
And your module signature would contain :
val b : t
This is especially useful when you need assumptions inside the module to be invisible to other modules. For instance, when using polymorphic variants:
let user_type = `Admin
Here, you only want to handle the administrator account, but you need the rest of your code to be aware that other account types exist, so you would write in the signature that:
val user_type : [`Admin|`Member|`Guest]
This type is technically correct, but could not have been guessed by the type inference algorithm.
精彩评论