Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type declaration in tuple unpacking

Tags:

ocaml

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?

like image 424
Nick Heiner Avatar asked Jan 18 '23 05:01

Nick Heiner


1 Answers

The syntax let x : t = … is the no-argument case of the more general syntax

let f a1 … an : t = …

where t is the return type of the function f. The identifier f has to be just an identifier, you can't have a pattern there. You can also write something like

let (x, y) = …

Here (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 write

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

Note that this annotation is useless except for some cosmetic report messages; x and y still have the type int, and (x, y) has the type int * int anyway. If you don't want coordinates to be the same type as integers, you need to introduce a constructor:

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

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:

let longitude (c : coords) = match c with Coords (x, y) -> x
like image 85
Gilles 'SO- stop being evil' Avatar answered Jan 25 '23 02:01

Gilles 'SO- stop being evil'