gpt4 book ai didi

haskell - 异构列表的显示实例

转载 作者:行者123 更新时间:2023-12-02 06:13:43 26 4
gpt4 key购买 nike

我在为下面定义的异构列表定义 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

关于haskell - 异构列表的显示实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50318757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com