I'm playing around with what tools haskell offers for dependently typed programming. I have promoted a GADT representing natural numbers to the kind level and made a type family for addition of natural numbers. I have also made your standard "baby's first dependently typed datatype" vector, parameterized over both its length and the type it contains. The code is as follows:
data Nat where
Z :: Nat
S :: Nat -> Nat
type family (a :: Nat) + (b :: Nat) :: Nat where
Z + n = n
S m + n = S (m + n)
data Vector (n :: Nat) a where
Nil :: Vector Z a
Cons :: a -> Vector n a -> Vector (S n) a
Furthermore I have made an append
function that takes an m-vector, an n-vetor and return an (m+n)-vector. This works as well as one might hope. However, just for the heck of it, I tried to flip it around so it returns an (n+m)-vector. This produces a compiler error though, because GHC can't prove that my addition is commutative. I'm still relatively new to type families, so I'm not sure how to write this proof myself, or if that's even something you can do in haskell.
My initial thought was to somehow utilize a type equality constraint, but I'm not sure how to move forward.
So to be clear: I want to write this function
append :: Vector m a -> Vector n a -> Vector (n + m) a
append Nil xs = xs
append (Cons x xs) ys = x `Cons` append xs ys
but it fails to compile with
* Could not deduce: (n + 'Z) ~ n
from the context: m ~ 'Z
bound by a pattern with constructor: Nil :: forall a. Vector 'Z a,
in an equation for `append'
unsafeCoerce
is the most sensible fix.TypeLits
.