[英]Evidence that two natural numbers are not equal?
Using Shapeless's Nat
type, how can I derive evidence that two natural numbers are not equal? 使用Shapeless的
Nat
类型,如何得出两个自然数不相等的证据?
This is what I have so far, but it only proves that a given Nat
is not equal to 0. How can I prove that any two Nat
values are not equal? 到目前为止,这就是我所拥有的,但是它仅证明给定的
Nat
不等于0。我如何证明任何两个Nat
值都不相等?
trait NEq[A <: Nat, B <: Nat] extends Serializable
object NEq {
def apply[A <: Nat, B <: Nat](implicit neq: A != B): NEq[A, B] = neq
type !=[A <: Nat, B <: Nat] = NEq[A, B]
implicit def neq1[B <: Nat] = new !=[Succ[B], _0] {}
implicit def neq2[B <: Nat] = new !=[_0, Succ[B]] {}
}
Using Shapeless's =:!=
is the easiest way to accomplish this, but it's not very generalizable (what if you need to show that two numbers differ by one, etc.?), and often when I start out using it I end up switching to a custom type class. 使用Shapeless的
=:!=
是完成此操作的最简单方法,但是它不是很通用(如果您需要显示两个数字相差一个,等等?),通常当我开始使用它时,我最终会切换到自定义类型类。
Your NEq
is only missing one piece—you've got the base cases, but you need the inductive step. 您的
NEq
仅缺一小部分-您已经有了基本案例,但是您需要归纳步骤。 You know that a Succ
is never _0
, but you also know that two Succ
s aren't the same if their contents aren't the same: 您知道一个
Succ
永远不会为_0
,但是您也知道两个Succ
的内容不相同的是不相同的:
trait NEq[A <: Nat, B <: Nat] extends Serializable
object NEq {
def apply[A <: Nat, B <: Nat](implicit neq: A != B): NEq[A, B] = neq
type !=[A <: Nat, B <: Nat] = NEq[A, B]
implicit def neq1[B <: Nat]: Succ[B] != _0 = new !=[Succ[B], _0] {}
implicit def neq2[B <: Nat]: _0 != Succ[B] = new !=[_0, Succ[B]] {}
implicit def neq3[A <: Nat, B <: Nat](implicit neq: A != B): Succ[A] != Succ[B] =
new !=[Succ[A], Succ[B]] {}
}
This will work as expected. 这将按预期工作。
Why not: 为什么不:
def neq[A <: Nat, B <: Nat](implicit ev: A <:!< B) = ev
Example: 例:
scala> neq[_1, _2]
res8: shapeless.<:!<[shapeless.nat._1,shapeless.nat._2] = shapeless.package$$anon$2@7db44dae
scala> neq[_1, _1]
<console>:15: error: ambiguous implicit values:
both method nsubAmbig1 in package shapeless of type [A, B >: A]=> shapeless.<:!<[A,B]
and method nsubAmbig2 in package shapeless of type [A, B >: A]=> shapeless.<:!<[A,B]
match expected type shapeless.<:!<[shapeless.nat._1,shapeless.nat._1]
neq[_1, _1]
^
See also: Type constraint for type inequality in scala 另请参阅: scala中类型不等式的类型约束
And this , just in case if you want to check it in runtime for some reason. 而这 ,以防万一您出于某种原因想要在运行时检查它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.