How to construct a tuple with only one element in standard ML?

Viewed 105

In standard ML (Standard ML of New Jersey), we use following syntax to construct tuple

val x = (1, 2);
val u = ();

However we can not construct tuple with only one element

val x = (1); (* normal int *)
val y = (1,); (* python syntax, not valid in SML *)

On the other hand, one element tuple and element itself seems have same type signature.

Can we distinct 'a and a tuple with only one element of type 'a in SML? If so, how can we construct a one element tuple and what's type signature of it?

1 Answers

Can we distinct 'a and a tuple with only one element of type 'a in SML?

Yes, you can.

Unlike Python, there isn't any special (1,) syntax. But since tuples are equivalent to records with numbered fields, you can create a record with exactly one field named 1 and access it using the #1 macro for getting the first value of a tuple:

- val foo = { 1 = 42 };
val foo = {1=42} : {1:int}

- #1 foo;
val it = 42 : int

You can see that this is actually a 1-tuple by trying to annotate a regular 2-tuple as a record:

- (3.14, "Hello") : { 1 : real, 2 : string };
val it = (3.14,"Hello") : real * string

what's type signature of it?

The type would be { 1 : 'a }. You can preserve the type parameter like this:

type 'a one = { 1 : 'a };

You could get something similar using a datatype:

datatype 'a one = One of 'a
fun fromOne (One x) = x

I think those would use the same amount of memory.

Related