作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我有一个数据类型
data SomeType a =
Type a |
Mix (SomeType a) (SomeType a)
这是我的 SomeType 的显示实例
instance (Show a) => Show (SomeType a) where
show (Type a) = show a
show (Mix a b) = "(" ++ show a ++ " " ++ show b ++ ")"
所以
Mix (Type 5) (Type 4)
会给我
(5 4)
现在我想要
read "(3 4)" :: SomeType Int
生产
(3 4)
或
read "(a b)" :: SomeType Char
生产
(a b)
我不知道如何使用 Read 类。
最佳答案
这是一个基于 documentation 的示例它应该能够解析 show
呈现的所有内容(假设该类型定义了兼容的 Read
实例),即 read 。 show
或多或少应该是身份:
instance (Read a) => Read (SomeType a) where
readsPrec d r = readMix r ++ readType r
where
readMix = readParen True $ \r -> do
(v1, r'') <- readsPrec d r
(v2, r') <- readsPrec d r''
return (Mix v1 v2, r')
readType r = do
(v, r') <- readsPrec d r
return (Type v, r')
因此,
> read "(3 4)" :: SomeType Int
(3 4)
it :: SomeType Int
但请注意,对于 SomeType Char
,Char
的默认 Show
实例用单引号将字符括起来:
> read "('a' ('b' 'c'))" :: SomeType Char
('a' ('b' 'c'))
it :: SomeType Char
希望这有帮助
关于haskell - 如何在 haskell 中为数据类型创建 Read 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7851275/
我是一名优秀的程序员,十分优秀!