How to define abstract types in agda
1 answer
You can use parameterized modules. Let's look at an example: we start by introducing a Nats
packing record a Set
along with operations on it.
record Nats : Set₁ where
field
Nat : Set
zero : Nat
succ : Nat → Nat
primrec : {B : Set} (z : B) (s : Nat → B → B) → Nat → B
We can then define a module parameterized with such a structure. Addition and multiplication can be defined in terms of primitive recursion, null and successor.
open import Function
module AbstractType (nats : Nats) where
open Nats nats
add : Nat → Nat → Nat
add m n = primrec n (const succ) m
mult : Nat → Nat → Nat
mult m n = primrec zero (const (add n)) m
Finally, we can provide examples Nats
. Here I am reusing natural numbers defined in the standard library, but binary numbers can be used, for example.
open Nats
Natsℕ : Nats
Natsℕ = record { Nat = ℕ
; zero = 0
; succ = suc
; primrec = primrecℕ }
where
open import Data.Nat
primrecℕ : {B : Set} (z : B) (s : ℕ → B → B) → ℕ → B
primrecℕ z s zero = z
primrecℕ z s (suc n) = s n $ primrecℕ z s n
Passing this instance to the module gives us the corresponding add / mult operations:
open import Relation.Binary.PropositionalEquality
example :
let open AbstractType Natsℕ
in mult (add 0 3) 3 ≡ 9
example = refl
+7
source to share