我在为下面定义的异构列表定义 Show 实例时遇到问题:
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE FlexibleInstances #-}
import Data.Kind
data HList xs where
HNil :: HList TNil
(::^) :: a -> HList as -> HList (a :^ as)
data TypeList = TNil | (:^) Type TypeList
instance Show (HList TNil) where
show HNil = "[]"
我想给HList xs一个show实例,如果Typelist xs中的所有类型都有一个Show Instance。我想应该可以写出类似的东西
instance (Show a, _) => Show (HList a :^ as) where
show (x ::^ xs) = show x ++ show xs
但我不确定该填什么_。
PS:如果你在 ghci 中尝试这个,不要忘记添加语言扩展
:set -XTypeInType -XTypeOperators
请您参考如下方法:
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
import Data.Kind
infixr 5 ::^
data HList xs where
HNil :: HList TNil
(::^) :: a -> HList as -> HList (a :^ as)
data TypeList = TNil | (:^) Type TypeList
instance Show (HList TNil) where
show HNil = "HNil"
instance (Show a, Show (HList as)) => Show (HList (a:^as)) where
showsPrec p (x::^xs) = showParen (p>5)
$ showsPrec 6 x . ("::^"++) . showsPrec 5 xs
main :: IO ()
main = print ((2 :: Int) ::^ "bla" ::^ HNil)
2::^"bla"::^HNil