Created
June 23, 2021 00:38
-
-
Save johnynek/cf4597c35a1e9c4cd4e9db38a053c62d to your computer and use it in GitHub Desktop.
implementing typelevel Nat tracking in scala 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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