Lists of fixed length and type literals

前端 未结 2 885
栀梦
栀梦 2021-01-02 08:22

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

2条回答
  •  天涯浪人
    2021-01-02 08:55

    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.

提交回复
热议问题