gpt4 book ai didi

haskell - Show for String的实例是怎么写的?

转载 作者:行者123 更新时间:2023-12-02 18:51:02 28 4
gpt4 key购买 nike

我有一个关于定义类型类实例的基本问题。我使用 Show 类型类作为示例,并且只考虑类中的 show 函数。像 Bool 这样的具体类型的 Show 实例很简单

instance Show Bool where
show x = {function of x here}

但对于字符串则不是:

instance Show String where
show x = {function of x here}

产生一个可以理解的错误

Illegal instance declaration for ‘Formatter String’
(All instance types must be of the form (T t1 ... tn)
where T is not a synonym.
Use TypeSynonymInstances if you want to disable this.)
In the instance declaration for ‘Formatter String’

当然,以下行为是不允许的:

instance Show [Char] where
show x = {function of x here}

我可以定义一个新类型

newtype String2 = String2 String 
instance Formatter String2 where
format (String2 x) = {function of x here}
然而,这不允许我像在 Haskell 中那样显示“测试”。

我缺少类型类的哪些基本功能?

最佳答案

Show typeclass 实际上有三个成员函数,show , showsPrec ,和showList 。在 Show Char 的实例中,showList函数被重载以输出引号并将所有字母推到一起,不带分隔符:

来自 GHC.Show :

instance  Show Char  where
showsPrec _ '\'' = showString "'\\''"
showsPrec _ c = showChar '\'' . showLitChar c . showChar '\''

showList cs = showChar '"' . showLitString cs . showChar '"'

哪里 showLitString 定义为:

showLitString :: String -> ShowS
-- | Same as 'showLitChar', but for strings
-- It converts the string to a string using Haskell escape conventions
-- for non-printable characters. Does not add double-quotes around the
-- whole thing; the caller should do that.
-- The main difference from showLitChar (apart from the fact that the
-- argument is a string not a list) is that we must escape double-quotes
showLitString [] s = s
showLitString ('"' : cs) s = showString "\\\"" (showLitString cs s)
showLitString (c : cs) s = showLitChar c (showLitString cs s)

所以没有Show String例如,很简单,Show Char定义如何调用show[Char]具体值。

关于haskell - Show for String的实例是怎么写的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27951718/

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