diff --git a/content/toc.md b/content/toc.md index 98756c3..a909f86 100644 --- a/content/toc.md +++ b/content/toc.md @@ -8,7 +8,7 @@ * [Types](/types/) * [Objects](/types/objects/) * [Enums](/types/enums/) - * [Distinct](/types/distinct/) + * [Distinct Types](/types/distinct/) * [If, Else, While, Block](/if_else_while/) * [Case Statements](/case/) * [Numbers](/numbers/) diff --git a/content/types.md b/content/types.md new file mode 100644 index 0000000..8ba8416 --- /dev/null +++ b/content/types.md @@ -0,0 +1,38 @@ +--- +title: Types +--- +# Types + +Types are declared inside type sections, where multiple types can be declared. Note that aliased types are the same, and not in any way incompatible with their original type. If type safety is desired, [distinct types](/types/distinct/) should be used. + +``` nimrod +type + MyInteger* = int + +let a: int = 2 +discard a + MyInteger(4) +``` + +## Range Types + +Range types that guarantee a value will always be within a given range also exist. Whenever possible, out-of-bounds values will fail at compile-time, otherwise they will fail at run-time. + +``` nimrod +type + TwoDigits* = range[10..99] + +let a = 2 +var b: TwoDigits = 99 + a # Fails at run-time +let c: TwoDigits = 100 # Fails at compile-time +``` + +Also note that range types also work on any other ordinal type, so a range over an enum is also valid: + +``` nimrod +type + MyEnum = enum + A, B, C, D, E + BToD = range[B..D] + +let value: BToD = C +``` \ No newline at end of file diff --git a/content/types/distinct.md b/content/types/distinct.md new file mode 100644 index 0000000..5881ebc --- /dev/null +++ b/content/types/distinct.md @@ -0,0 +1,24 @@ +--- +title: Distinct Types +--- +# Distinct Types + +Distinct types are like other type aliases, but they provide type safety so that it is impossible to coerce a distinct type into its base type without explicit conversion. + +``` nimrod +type + Dollars* = distinct float + +var a = 20.Dollars +a = 25 # Doesn't compile +a = 25.Dollars # Works fine +``` + +However, when using distinct types, none of the base type's procedures follow the type. To solve this, it is possible to create lots of procedures that basically act as a thin wrapper for the underlying types, or the `{.borrow.}` pragma can be used to automate generation of procedures. + +``` nimrod +proc `*` *(a, b: Dollars): Dollars {.borrow.} +proc `+` *(a, b: Dollars): Dollars {.borrow.} +a = 20.Dollars * 20.Dollars +``` + \ No newline at end of file