Agda Type-Checking and Commutativity / Associativity of +

前端 未结 1 986
庸人自扰
庸人自扰 2020-12-30 02:26

Since the _+_-Operation for Nat is usually defined recursively in the first argument, its obviously non-trivial for the type-checker to know that <

相关标签:
1条回答
  • 2020-12-30 03:06

    Teaching Agda that m == m + zero isn't too hard. For example, using the standard type for equality proofs, we can write this proof:

    rightIdentity : (n : Nat) -> n + 0 == n
    rightIdentity zero = refl
    rightIdentity (suc n) = cong suc (rightIdentity n)
    

    We can then tell Agda to use this proof using the rewrite keyword:

    swap : {A : Set} {m n : Nat} -> Vec A (n + m) -> Vec A (m + n)    
    swap {_} {m} {zero} xs rewrite rightIdentity m = xs 
    swap {_} {_} {suc i} (x :: xs) = ?
    

    However, providing the necessary proofs for the second equation is a lot more difficult. In general, it's a much better idea to try to make the structure of your computations match the structure of your types. That way, you can get away with a lot less theorem proving (or none in this case).

    For example, assuming we have

    drop : {A : Set} {m : Nat} -> (n : Nat) -> Vec A (n + m) -> Vec A m
    take : {A : Set} {m : Nat} -> (n : Nat) -> Vec A (n + m) -> Vec A n
    

    (both of which can be defined without any theorem proving), Agda will happily accept this definition without any fuss:

    swap : {A : Set} {m n : Nat} -> Vec A (n + m) -> Vec A (m + n)
    swap {_} {_} {n} xs = drop n xs ++ take n xs
    
    0 讨论(0)
提交回复
热议问题