为什么 Data.String.IsString 类型类只定义一种转换?
为什么 Haskell 基础包只定义 IsString
类来进行从 String
到 'like-string' 值的转换,而不定义从 'like- string' 值转换为String
?
该类应定义为:
class IsString a where
fromString :: String -> a
toString :: a -> String
ref: http://hackage.haskell.org/packages/archive/base/4.4.0.0/doc/html/Data-String.html
Why does the Haskell base package only define the IsString
class to have a conversion from String
to 'like-string' value, and not define the inverse transformation, from 'like-string' value to String
?
The class should be defined as:
class IsString a where
fromString :: String -> a
toString :: a -> String
ref: http://hackage.haskell.org/packages/archive/base/4.4.0.0/doc/html/Data-String.html
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
原因是恕我直言,
IsString
的主要目的是用于 Haskell 源代码(或 (E)DSL)中的字符串文字 - 另请参阅 Paradise:通过 OverloadedStrings 语言扩展嵌入 Haskell 中的两阶段 DSL),其方式与其他多态文字的工作方式类似(例如,通过fromRational
表示浮点文字,或通过fromInteger
表示整数文字)术语
IsString
可能有点误导,因为它表明该类型-class 表示类似字符串的结构,而它实际上只是表示在 Haskell 源代码中具有引用字符串表示形式的类型。The reason is IMHO that
IsString
's primary purpose is to be used for string literals in Haskell source code (or (E)DSLs -- see also Paradise: A two-stage DSL embedded in Haskell) via theOverloadedStrings
language extension in an analogous way to how other polymorphic literals work (e.g. viafromRational
for floating point literals orfromInteger
for integer literals)The term
IsString
might be a bit misleading, as it suggests that the type-class represents string-like structures, whereas it's really just to denote types which have a quoted-string-representation in Haskell source code.如果您想使用 toString :: a -> String,我想你只是忘记了
show :: a ->; String
,或更准确地说是Show a =>显示::a->字符串
。如果您想对具有
:: a -> 的类型进行操作String
和:: String -> a
,您可以简单地将这些类型类约束放在函数上。我们仔细注意,我们避免定义具有一组函数的类型类,这些函数也可以分为两个子类。因此,我们不会将
toString
放入IsString
中。最后,我还必须提到
Read
,它提供了Read a => 。字符串 ->一个。您可以使用
read
和show
进行非常简单的序列化。IsString
中的fromString
有不同的用途,它与语言编译指示OverloadedStrings
一起使用,那么你可以非常方便地插入类似"This 的代码不是字符串"::Text
。 (Text
是字符串的(高效)数据结构)If you desire to use
toString :: a -> String
, I think you're simply forgetting aboutshow :: a -> String
, or more properlyShow a => show :: a -> String
.If you want to operate on a type both having a
:: a -> String
and:: String -> a
, you can simply put those type-class constraints on the functions.We carefully note that we avoid defining type classes having a set of functions that can as well be split into two subclasses. Therefor we don't put
toString
inIsString
.Finally, I must also mention about
Read
, which providesRead a => String -> a
. You useread
andshow
for very simple serialization.fromString
fromIsString
has a different purpose, it's useful with the language pragmaOverloadedStrings
, then you can very conveniently insert code like"This is not a string" :: Text
. (Text
is a (efficient) data-structure for Strings)