Skip to content

Instantly share code, notes, and snippets.

@mattecapu
Last active June 22, 2019 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattecapu/432cc5a1bb702811f3208230f6580526 to your computer and use it in GitHub Desktop.
Save mattecapu/432cc5a1bb702811f3208230f6580526 to your computer and use it in GitHub Desktop.
Proof of equivalence for two definitions of sum.
# Proof of equivalence for two definitions of sum
\begin{code}
module equiv_of_sums where
import Relation.Binary.PropositionalEquality as Eq
open Eq using (_≡_; refl; cong; sym)
open Eq.≡-Reasoning using (begin_; _≡⟨⟩_; _≡⟨_⟩_; _∎)
data ℕ : Set where
zero : ℕ
suc : ℕ → ℕ
{-# BUILTIN NATURAL ℕ #-}
\end{code}
Since sum of naturals is a recursive function on both its entries, it admits two different definitions. The two definitions are not definitionally equivalent, as their definition makes apparent. However, we here prove they are propositionally equivalent, i.e. the two definitions yield equal same values on equal inputs.
The two are
* recursion on the first argument:
\begin{code}
_+₁_ : ℕ → ℕ → ℕ
_+₁_ zero n = n
_+₁_ (suc m) n = suc (m +₁ n)
\end{code}
* recursion on the second argument:
\begin{code}
_+₂_ : ℕ → ℕ → ℕ
_+₂_ n zero = n
_+₂_ n (suc m) = suc (n +₂ m)
\end{code}
We use here a proof which rests on the commutativity of the sum. Hence we show that the two definitions are the same up to an exchange of the arguments, which we know is an operation which preserves the result.
Therefore, we begin by proving `+₁' is commutative. The proof is slightly non-trivial, because we need to induct on the proof.
\begin{code}
+₁-id : ∀ (x : ℕ) → x +₁ zero ≡ x
+₁-id zero = refl
+₁-id (suc x) =
begin
(suc x) +₁ zero
≡⟨⟩
suc (x +₁ zero)
≡⟨ cong suc (+₁-id x) ⟩
suc x
+₁-suc : ∀ (x y : ℕ) → x +₁ suc y ≡ suc (x +₁ y)
+₁-suc zero y = refl
+₁-suc (suc x) y =
begin
suc x +₁ suc y
≡⟨⟩
suc (x +₁ suc y)
≡⟨ cong suc (+₁-suc x y) ⟩
suc (suc (x +₁ y))
≡⟨⟩
suc (suc x +₁ y)
+₁-comm : ∀ (x y : ℕ) → x +₁ y ≡ y +₁ x
+₁-comm x zero = +₁-id x
+₁-comm x (suc y) =
begin
x +₁ suc y
≡⟨ +₁-suc x y ⟩
suc (x +₁ y)
≡⟨ cong suc (+₁-comm x y) ⟩
suc (y +₁ x)
≡⟨⟩
suc y +₁ x
\end{code}
We are now ready to prove our main result.
\begin{code}
+₁-is-swapped-+₂ : ∀ (x y : ℕ) → x +₁ y ≡ y +₂ x
+₁-is-swapped-+₂ zero y =
begin
zero +₁ y
≡⟨⟩
y
≡⟨⟩
y +₂ 0
+₁-is-swapped-+₂ (suc x) y =
begin
suc x +₁ y
≡⟨⟩
suc (x +₁ y)
≡⟨ cong suc (+₁-is-swapped-+₂ x y) ⟩
suc (y +₂ x)
≡⟨⟩
y +₂ suc x
+₁=+₂ : ∀ (x y : ℕ) → x +₁ y ≡ x +₂ y
+₁=+₂ x y =
begin
x +₁ y
≡⟨ +₁-comm x y ⟩
y +₁ x
≡⟨ +₁-is-swapped-+₂ y x ⟩
x +₂ y
\end{code}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment