我的疑惑: 我们只能将 Functor 实例写入任何可以产生类型输出的数据类型(例如:[a], Maybe a, (y -> a)),但不能用于消耗类型的数据类型。 现在,在上述数据键入它消耗了功能消耗了那么请问这个间接消耗的可视为生产类型。 这意味着我们不能为(k -> a) ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
我有一个关于定义类型类实例的基本问题。 我使用Show类型类作为示例,我只考虑类中的函数show。 像Bool这样的具体类型的Show实例很简单
instance Show Bool where
show x = {function of x here}
但对于String,它不是:
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
类型类实际上有三个成员函数, 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
定义了如何在[Char]
值上专门调用show
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.