I\'m trying to define a type for lists of fixed length in Haskell. When I use the standard way to encode natural numbers as types in unary, everything works fine. However, w
This is not really an answer.
Using https://hackage.haskell.org/package/ghc-typelits-natnormalise-0.2 , this
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}
import GHC.TypeLits
data List (n :: Nat) a where
Nil :: List 0 a
(:>) :: a -> List n a -> List (n+1) a
append :: List n1 a -> List n2 a -> List (n1 + n2) a
append Nil ys = ys
append (x :> xs) ys = x :> (append xs ys)
... compiles, so obviously it's correct.
Type level number literals don't yet have a structure on which we can do induction, and the built-in constraint solver can only figure out the simplest cases. Currently it's better to stick with Peano naturals.
However, we can still use the literals as syntactic sugar.
{-# LANGUAGE
UndecidableInstances,
DataKinds, TypeOperators, TypeFamilies #-}
import qualified GHC.TypeLits as Lit
data Nat = Z | S Nat
type family Lit n where
Lit 0 = Z
Lit n = S (Lit (n Lit.- 1))
Now you can write List (Lit 3) a
instead of List (S (S (S Z))) a
.