在元组解包中键入声明

Nic*_*ner 4 ocaml

给定类型:

type coords = int * int 
Run Code Online (Sandbox Code Playgroud)

以下作品:

# let c : coords = 3, 4;;
val c : coords = (3, 4)
Run Code Online (Sandbox Code Playgroud)

我也希望能够做到:

# let (x, y) : coords = 3, 4;;
  let (x, y) : coords = 3, 4;;
Error: Syntax error
Run Code Online (Sandbox Code Playgroud)

但它抱怨语法错误:.这在语法上是否可行?

Gil*_*il' 8

语法let x : t = …是更一般语法的无参数情况

let f a1 … an : t = …
Run Code Online (Sandbox Code Playgroud)

其中t是函数的返回类型f.标识符f必须只是一个标识符,你不能在那里有一个模式.你也可以写点东西

let (x, y) = …
Run Code Online (Sandbox Code Playgroud)

(x, y)是一种模式.类型注释可以出现在模式中,但必须用括号括起来(如表达式中所示),因此需要编写

let ((x, y) : coords) = …
Run Code Online (Sandbox Code Playgroud)

请注意,除了一些化妆品报告消息之外,此注释是无用的; x并且y仍然有类型int,并且无论如何(x, y)都有类型int * int.如果您不希望坐标与整数的类型相同,则需要引入构造函数:

type coords = Coords of int * int
let xy = Coords (3, 4)
Run Code Online (Sandbox Code Playgroud)

如果这样做,单个坐标仍然是整数,但是一对坐标是具有自己类型的构造对象.要获得一个坐标的值,构造函数必须包含在模式匹配中:

let longitude (c : coords) = match c with Coords (x, y) -> x
Run Code Online (Sandbox Code Playgroud)