Limited support for nominal typing in Motoko

Are there any plans to add limited support for nominal (as opposed to structural) typing in Motoko?

So that would let us define two separate types:

type Kilometer = Float;
type Mile = Float;

without the Motoko type checker treating them as equivalent.

You could do something like this:

type Kilometer = { #kilometer : Float };
type Mile = { #mile : Float };

This is an approximation of what some languages call a “newtype” or “newtype wrapper”.

1 Like

Hmm yeah that’s actually not a bad idea.

FWIW there used to be some runtime constructs to this effect (as evidenced by the following issue)

Oh wow, didn’t know Motoko dated back to 2018.

Going back to the newtype idiom, I wish Motoko had the “tuple struct” construct that Rust has, so I could omit the #kilometer in type Kilometer = { #kilometer : Float };…

Without the tag you wouldn’t be able to construct a value of that type though.

Well, not being able to omit it is the whole point of the pattern, since it determines and makes explicit which unit is being used.

FWIW, a singleton record {km : Float} would work just as well.

There never were nominal types in the language, I believe we were merely hypothesising on that issue. Nominal types are rather problematic in a distributed setting, since somebody will “own” their definition locally. That is, you cannot really use them easily for messaging. So it was natural to avoid them altogether.

4 Likes