Given a type:
type coords = int * int
The following works:
# let c : coords = 3, 4;;
val c : coords = (3, 4)
I would also like to be able to do:
# let (x, y) : coords = 3, 4;;
let (x, y) : coords = 3, 4;;
Error: Syntax error
But it complains about a syntax error on :. Is this syntactically possible?
The syntax
let x : t = …is the no-argument case of the more general syntaxwhere
tis the return type of the functionf. The identifierfhas to be just an identifier, you can’t have a pattern there. You can also write something likeHere
(x, y)is a pattern. Type annotations can appear in patterns, but they must be surrounded by parentheses (like in expressions), so you need to writeNote that this annotation is useless except for some cosmetic report messages;
xandystill have the typeint, and(x, y)has the typeint * intanyway. If you don’t want coordinates to be the same type as integers, you need to introduce a constructor:If you do that, an individual coordinate is still an integer, but a pair of coordinates is a constructed object that has its own type. To get at the value of one coordinate, the constructor must be included in the pattern matching: