Skip to content

Instantly share code, notes, and snippets.

@johnynek
Created June 23, 2021 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnynek/cf4597c35a1e9c4cd4e9db38a053c62d to your computer and use it in GitHub Desktop.
Save johnynek/cf4597c35a1e9c4cd4e9db38a053c62d to your computer and use it in GitHub Desktop.
implementing typelevel Nat tracking in scala 3
package example
sealed trait Nat
case object Zero extends Nat
case class Succ[N <: Nat](n: N) extends Nat
type Inc[N <: Nat] <: Nat =
N match {
case Zero.type => Succ[Zero.type]
case Succ[n] => Succ[Inc[n]]
}
object Nat {
def inc[N <: Nat](n: N): Inc[N] =
// it's important to match on the type below, or it won't unify (for some reason)
n match {
case _: Zero.type => Succ(Zero)
case s: Succ[a] => Succ(inc(s.n))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment