以下代码是Idris:
natAssociative : (a : Nat) -> (b : Nat) -> (c : Nat) -> (a + b) + c = a + (b + c)
natAssociative Z b c = the (b + c = b + c) refl
natAssociative (S k) b c = replace {P=\x => S (k + b) + c = S x} (natAssociative k b c) refl
我正在艰难地将其转化为无形。我尝试了一些不同的编码,但我认为这是最有希望的开始:
import scalaz.Leibniz._
import shapeless.{ HNil, Nat, Succ, Poly3 }
import shapeless.Nat._
import shapeless.ops.nat._
object natAssociative extends Poly3 {
implicit def case0[B <: Nat, C <: Nat]: Case[_0, B, C] = at[_0, B, C] {
case (Nat._0, b, c) => refl[Sum[B, C]#Out]
}
implicit def caseSucc[K <: Nat, B <: Nat, C <: Nat] = ???
}
我在导入方面遇到了麻烦,并且让Scala认识到我们有两种可能的情况要归还。编码这部分有诀窍吗?
答案 0 :(得分:5)
Nat
和Sum
的定义无形,你无法真正证明什么。因为Sum
不是函数,具有相同的参数,我们可以得到不同的结果:
object Pooper {
implicit def invalidSum: Sum[_1, _1] = new Sum[_1, _1] {
type Out = _3
}
}
但是如果我们定义自然和总和有点不同:
package plusassoc
import scala.language.higherKinds
import scalaz.Leibniz
sealed trait Nat {
type Add[A <: Nat] <: Nat // 1.add(5)
}
case class Zero() extends Nat {
type Add[A <: Nat] = A
}
case class Succ[N <: Nat]() extends Nat {
type Add[A <: Nat] = Succ[N#Add[A]]
}
// a for aliases
package object a {
// Equality on nats
type ===[A <: Nat, B <: Nat] = Leibniz[Nothing, Nat, A, B]
type Plus[A <: Nat, B <: Nat] = A#Add[B]
type One = Succ[Zero]
type Two = Succ[One]
type Three = Succ[Two]
}
import a._
Add
(和Plus
)现在是行为良好的类型级函数。
然后我们可以写出Plus
:
/*
plus-assoc : ∀ n m p → (n + (m + p)) ≡ ((n + m) + p)
plus-assoc zero m p = refl
plus-assoc (suc n) m p = cong suc (plus-assoc n m p)
*/
trait PlusAssoc[N <: Nat, M <: Nat, P <: Nat] {
val proof: Plus[N,Plus[M, P]] === Plus[Plus[N, M], P]
}
object PlusAssoc {
implicit def plusAssocZero[M <: Nat, P <: Nat]: PlusAssoc[Zero, M, P] = new PlusAssoc[Zero, M, P] {
val proof: Plus[M,P] === Plus[M,P] = Leibniz.refl
}
implicit def plusAssocSucc[N <: Nat, M <: Nat, P <: Nat](implicit
ih: PlusAssoc[N, M, P]): PlusAssoc[Succ[N], M, P] = new PlusAssoc[Succ[N], M, P] {
// For some reason scalac fails to infer right params for lift :(
val proof: Succ[Plus[N,Plus[M, P]]] === Succ[Plus[Plus[N, M], P]] = Leibniz.lift[
Nothing, Nothing,
Nat, Nat,
Succ,
Plus[N, Plus[M, P]], Plus[Plus[N, M], P]
](ih.proof)
}
}
由于我们依赖于隐含,我们必须测试scalac是否可以使用我们的&#34;规则真正构建证据&#34;:
import plusassoc._
import plusassoc.a._
import plusassoc.PlusAssoc._
implicitly[PlusAssoc[One, Two, Three]].proof
res0: ===[Plus[One,Plus[Two,Three]],Plus[Plus[One,Two],Three]] = scalaz.LeibnizFunctions$$anon$2@7b2c4c00
// with plusassoc.a. prefix skipped