Type-level `Nat`
- LucianoOP 2
I see in the stdlib documentation there is a
data Nat.Am I correct in thinking these are not Peano numerals i.e.
data Nat = Zero | Succ Nat, but something internal to the compiler?Otherwise, how can I create a value of this type? The constructors don’t appear to be exported.
I also tried looking through the code-base, and I can see a lot of references to
TypeLevelNat. - Sofia_Faro 4
Short answer:
Natisn’t a type you can construct. It’s a “kind” used by the compiler to make sure thatNumerictypes are well-defined. There are no values of typeNat, but when an integer appears in a type expression, the integer has kindNat.Long answer: When you write a
Numerictype, you need to specify the scale. For example:-
Numeric 10is the type of decimal numbers with 10 digits after the decimal point. -
Numeric 20is the type of decimal numbers with 20 digits after the decimal point. -
Numeric 30is the type of decimal numbers with 30 digits after the decimal point. - etc.
So
Numeric nis a well-formed type, but what sort of thing is the numbernin this type expression? Because it occurs inside a type expression, we could call it a “type”, but it doesn’t behave like other types. For example, there’s no such thing as a value of of type10, and you can’t create functions from the type10, etc.Instead, to distinguish
nfrom the usual sort of type, we say thatnhas a different “kind”. Its kind isNat. Any numbers appearing in type expressions will have kindNat, andNumericexpects a "type of kindNat" as its only type argument.Does this mean DAML supports integer arithmetic at the type level? No, because
Natis very limited. It exists in its current form only to makeNumericwork, so it has some big limitations, and I would recommend against usingNatin your own DAML projects.Here’s some of the limitations of the
Natkind:-
Nat“types” must range between0and37inclusive.* - There are no (type-level) arithmetic operations for kind
Nat. - You cannot convert a
Nattype to anIntvalue directly.** - Support for
Natin DAML-LF is even more limited.
*- The range limitation is in place because
Numericis similarly limited: you can only haveNumeric 0throughNumeric 37.**- The indirect solution to this is to use a
NumericScaleconstraint, which gives you access to thenumericScalefunction, which converts the type-level number into an integer value. This is mostly intended for library authors who need to work generically in the scale of aNumeric. -