Using Church encoding, it is possible to represent any arbitrary algebraic datatype without using the built-in ADT system. For example, Nat
can be represented (example in Idris) as:
-- Original type
data Nat : Type where
natSucc : Nat -> Nat
natZero : Nat
-- Lambda encoded representation
Nat : Type
Nat = (Nat : Type) -> (Nat -> Nat) -> Nat -> Nat
natSucc : Nat -> Nat
natSucc pred n succ zero = succ (pred n succ zero)
natZero : Nat
natZero n succ zero = zero
Pair
can be represented as:
-- Original type
data Pair_ : (a : Type) -> (b : Type) -> Type where
mkPair_ : (x:a) -> (y:b) -> Pair_ a b
-- Lambda encoded representation
Par : Type -> Type -> Type
Par a b = (t:Type) -> (a -> b -> t) -> t
pair : (ta : Type) -> (tb : Type) -> (a:ta) -> (b:tb) -> Par ta tb
pair ta tb a b k t = t a b
fst : (ta:Type) -> (tb:Type) -> Par ta tb -> ta
fst ta tb pair = pair ta (\ a, b => a)
snd : (ta:Type) -> (tb:Type) -> Par ta tb -> tb
snd ta tb pair = pair tb (\ a, b => b)
And so on. Now, writing those types, constructors, matchers is a very mechanical task. My question is: would it be possible to represent an ADT as a specification on the type level, then derive the types themselves (i.e., Nat
/Par
), as well as the constructors/destructors automatically from those specifications? Similarly, could we use those specifications to derive generics? Example:
NAT : ADT
NAT = ... some type level expression ...
Nat : Type
Nat = DeriveType NAT
natSucc : ConstructorType 0 NAT
natSucc = Constructor 0 NAT
natZero : ConstructorType 1 NAT
natZero = Constructor 1 NAT
natEq : EqType NAT
natEq = Eq NAT
natShow : ShowType NAT
natShow = Show NAT
... and so on
Bool = (A : Type) -> A -> A -> A
, andtru,fls
are defined accordingly, you can't prove(b: Bool) -> (b = tru \/ b = fls)
, while you could with inductive types. – EtruriaNat
then is an eliminatorNat = (P : Nat -> Type) -> (forall n. P n -> P (succ n)) -> P 0 -> forall n. P n
. I wrote a blog post about this.EqType
is derivable too (an example). How much types do you want to cover? Just System F types and no GADTs? – Torbert