Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Last active April 26, 2021 23:54
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 louisswarren/a93d89b662a2853d0cc0d86fffd01fef to your computer and use it in GitHub Desktop.
Save louisswarren/a93d89b662a2853d0cc0d86fffd01fef to your computer and use it in GitHub Desktop.
W-types in agda
-- Based on https://mazzo.li/epilogue/index.html%3Fp=324.html
data W (S : Set) (P : S → Set) : Set where
_◁_ : (s : S) → (P s → W S P) → W S P
data 𝟘 : Set where
data 𝟙 : Set where
● : 𝟙
data 𝟚 : Set where
▼ : 𝟚
▲ : 𝟚
Ψ : {A : Set} → 𝟘 → A
Ψ ()
-- Natural numbers
ℕ : Set
ℕ = W 𝟚 λ { ▼ → 𝟘; ▲ → 𝟙 }
zero : ℕ
suc : ℕ → ℕ
zero = ▼ ◁ Ψ
suc n = ▲ ◁ λ { ● → n }
-- Finite types
Fin : ℕ → Set
Fin n = W 𝟚 λ { ▼ → 𝟘; ▲ → 𝟙 }
fzero : ∀{n} → Fin (suc n)
fzero = ▼ ◁ Ψ
fsuc : ∀{n} → Fin n → Fin (suc n)
fsuc x = ▲ ◁ λ { ● → x }
-- Unlabelled binary trees
Tree : Set
Tree = W 𝟚 λ { ▼ → 𝟘; ▲ → 𝟚 }
leaf : Tree
node : Tree → Tree → Tree
leaf = ▼ ◁ Ψ
node l r = ▲ ◁ λ { ▼ → l; ▲ → r }
-- Sigma types
data Σ (S : Set) (P : S → Set) : Set where
_,_ : (s : S) → P s → Σ S P
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment