Type declaration in tuple unpacking

Given the 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:

 # let (x, y) : coords = 3, 4;; let (x, y) : coords = 3, 4;; Error: Syntax error 

But he complains about a syntax error on : Is this possible syntactically?

+4
source share
2 answers

Syntax let x : t = … is an argument without an argument of a more general syntax

 let f a1 … an : t = … 

where t is the return type of the function f . The identifier f should be just an identifier, you cannot have a template. You can also write something like

 let (x, y) = … 

Here (x, y) is the pattern. Type annotations can appear in templates, but they must be surrounded by brackets (for example, in expressions), so you need to write

 let ((x, y) : coords) = … 

Please note that this annotation is useless, with the exception of some cosmetic report messages; x and y are still of type int , and (x, y) is of type int * int . If you do not want the coordinates to be of the same type as integers, you need to enter a constructor:

 type coords = Coords of int * int let xy = Coords (3, 4) 

If you do this, the individual coordinate is still an integer, but the coordinate pair is a constructed object that has its own type. To get the value of one coordinate, the constructor must be included in the pattern matching:

 let longitude (c : coords) = match c with Coords (x, y) -> x 
+7
source

Syntax

 let x : t = ... 

means that in most cases you do not need to tell the compiler that the type of the name is x t (or maybe you just want to add this type of information for readability). In your example:

 let (x,y) : coords = 

you must ask yourself: what name is coords ? Obviously, you are not defining such a name, type x is int, and therefore is type y. On the left side there is no name with type coords. If you already have a coords value, you can break it down as shown below:

 # type coords = int*int ;; type coords = int * int # let c:coords = 3,4 ;; val c : coords = (3, 4) # let x,y = c;; val x : int = 3 val y : int = 4 

In the above example on line

 let c: coords = 3,4 ;; 

you are actually letting the compiler assign the name c to the coords type (otherwise int * int will be used as the type).

+1
source

Source: https://habr.com/ru/post/1401698/


All Articles