Skip to content

Instantly share code, notes, and snippets.

@keynmol
Created April 21, 2026 12:33
Show Gist options
  • Select an option

  • Save keynmol/1ea43676bae7418fde1010f590b37c7d to your computer and use it in GitHub Desktop.

Select an option

Save keynmol/1ea43676bae7418fde1010f590b37c7d to your computer and use it in GitHub Desktop.
Defining Scala 3 Native compile time numbers using match types
//> using scala 3.8
//> using platform native
import scalanative.unsafe.*
@main def hello =
Zone:
// Defining constant arrays in Scala Native
// Here we try to allocate a 1567891 byte array
// Old way, boooooo booo
val arr = alloc[CArray[
Byte,
Nat.Digit7[Nat._1, Nat._5, Nat._6, Nat._7, Nat._8, Nat._9, Nat._1]
]]()
// New, glorious way
val arr2 = alloc[CArray[
Byte,
Natty[1567891]
]]()
assert(arr.length == arr2.length)
end hello
import compiletime.ops.int.*, scala.compiletime.ops.boolean.*
import Nat.*
type NattyBase[X <: Int] <: Nat.Base = X match
case 0 => _0
case 1 => _1
case 2 => _2
case 3 => _3
case 4 => _4
case 5 => _5
case 6 => _6
case 7 => _7
case 8 => _8
case 9 => _9
type Natty[X <: Int] <: Nat = (X < 10) match
case true => NattyBase[X]
case false =>
(X < 100) match
case true => Digit2[NattyBase[X / 10], NattyBase[X % 10]]
case false =>
(X < 1000) match
case true =>
Digit3[NattyBase[X / 100], NattyBase[(X % 100) / 10], NattyBase[
X % 10
]]
case false =>
(X < 10000) match
case true =>
Digit4[NattyBase[X / 1000], NattyBase[
(X % 1000) / 100
], NattyBase[(X % 100) / 10], NattyBase[X % 10]]
case false =>
(X < 100000) match
case true =>
Digit5[
NattyBase[X / 10000],
NattyBase[(X % 10000) / 1000],
NattyBase[(X % 1000) / 100],
NattyBase[(X % 100) / 10],
NattyBase[X % 10]
]
case false =>
(X < 1_000_000) match
case true =>
Digit6[
NattyBase[X / 100000],
NattyBase[(X % 100000) / 10000],
NattyBase[(X % 10000) / 1000],
NattyBase[(X % 1000) / 100],
NattyBase[(X % 100) / 10],
NattyBase[X % 10]
]
case false =>
(X < 10_000_000) match
case true =>
Digit7[
NattyBase[X / 1000000],
NattyBase[(X % 1000000) / 100000],
NattyBase[(X % 100000) / 10000],
NattyBase[(X % 10000) / 1000],
NattyBase[(X % 1000) / 100],
NattyBase[(X % 100) / 10],
NattyBase[X % 10]
]
case false =>
(X < 100_000_000) match
case true =>
Digit8[
NattyBase[X / 10000000],
NattyBase[(X % 10000000) / 1000000],
NattyBase[(X % 1000000) / 100000],
NattyBase[(X % 100000) / 10000],
NattyBase[(X % 10000) / 1000],
NattyBase[(X % 1000) / 100],
NattyBase[(X % 100) / 10],
NattyBase[X % 10]
]
case false =>
(X < 1_000_000_000) match
case true =>
Digit9[
NattyBase[X / 100000000],
NattyBase[(X % 100000000) / 10000000],
NattyBase[(X % 10000000) / 1000000],
NattyBase[(X % 1000000) / 100000],
NattyBase[(X % 100000) / 10000],
NattyBase[(X % 10000) / 1000],
NattyBase[(X % 1000) / 100],
NattyBase[(X % 100) / 10],
NattyBase[X % 10]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment