Last active
May 8, 2019 04:06
-
-
Save mads-hartmann/6460968 to your computer and use it in GitHub Desktop.
This file contains 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
object Peano { | |
sealed trait Nat | |
trait Zero extends Nat | |
object ZeroV extends Zero | |
case class Succ[A <: Nat](x: A) extends Nat | |
trait Sum[A <: Nat, B <: Nat] { | |
type Out <: Nat | |
} | |
object Sum { | |
type Aux[A <: Nat, B <: Nat, C <: Nat] = Sum[A, B] { | |
type Out = C | |
} | |
implicit def baseCase[B <: Nat]: Aux[Zero, B, B] = | |
new Sum[Zero, B] { | |
type Out = B | |
} | |
implicit def inductiveStep[A <: Nat, B <: Nat] | |
(implicit sum: Sum[A, Succ[B]]): Aux[Succ[A], B, sum.Out] = new Sum[Succ[A], B] { | |
type Out = sum.Out | |
} | |
} | |
/* | |
Doesn't compile as we can't convience the compiler that b.type =:= sum.Out | |
Do so we need to a concise way of constraining the Out member of Plus. Like the | |
"Aux" type we use above, but I can't figure out the details. | |
found : b.type (with underlying type B) | |
required: sum.Out | |
case ZeroV => b | |
^ | |
*/ | |
def plus[A <: Nat, B <: Nat](a: A, b: B) | |
(implicit sum: Sum[A, B]): sum.Out = a match { | |
case ZeroV => b | |
// case Succ(q) => plus(q, Succ(b)) | |
} | |
plus(ZeroV: Zero, Succ[Zero](ZeroV)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a simple example of how to make it work: