Show for String实例如何写入?

我有一个关于定义类型类的基本问题。 我使用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类型类实际上有三个成员函数, showshowsPrecshowList 。 在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定义了如何在[Char]值中专门调用show

链接地址: http://www.djcxy.com/p/7539.html

上一篇: How is the instance of Show for String written?

下一篇: Using custom instance when deriving an instance via GeneralizedNewtypeDeriving