如何在haskell中为数据类型创建Read的实例 [英] How to create instance of Read for a datatype in haskell
本文介绍了如何在haskell中为数据类型创建Read的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个数据类型
data SomeType a =
键入a |
Mix(SomeType a)(SomeType a)
p>
instance(显示a)=> Show(SomeType a)
show(Type a)= show a
show(Mix ab)=(++ show a ++++ show b ++)
所以
Mix(Type 5)(Type 4)
会给我
(5 4)
现在我想拥有
阅读(3 4):: SomeType Int
产生
(3 4)
或
读取(ab):: SomeType Char
产生
(ab)
我是丢失在如何使用Read类。
解决方案以下是一个基于文档,它应该能够解析
展示
渲染(假设类型具有兼容的Read
实例定义),即read。
instance(阅读a)=>显示
应该或多或少地是身份: Read(SomeType a)其中
readsPrec d r = readMix r ++ readType r
其中
readMix = readParen True $ \r - > (v1,v2,r')$ b(v1,r'')< - readsPrec dr
(v2,r')< - readsPrec d r''
return
$ b readType r = do
(v,r')< - readsPrec dr
return(Type v,r')
因此,
>阅读(3 4):: SomeType Int
(3 4)
it :: SomeType Int
但是请注意,
SomeType Char 默认
显示
Char
用单引号括住字符:>阅读('a'('b''c')):: SomeType Char
('a'('b''c'))
it :: SomeType Char
希望这有助于
So I have a data type
data SomeType a = Type a | Mix (SomeType a) (SomeType a)
This my show instance for SomeType
instance (Show a) => Show (SomeType a) where show (Type a) = show a show (Mix a b) = "(" ++ show a ++ " " ++ show b ++ ")"
So
Mix (Type 5) (Type 4)
would give me
(5 4)
Now I want to have
read "(3 4)" :: SomeType Int
produce
(3 4)
or
read "(a b)" :: SomeType Char
produce
(a b)
I am lost at how to use the Read class.
解决方案Here's an example based on the documentation which should be able to parse everything that
show
renders (assuming the type has a compatibleRead
instance defined), that isread . show
should be more or less the identity: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')
Thus,
> read "(3 4)" :: SomeType Int (3 4) it :: SomeType Int
But note, that for
SomeType Char
the defaultShow
instance ofChar
surrounds the character with single quotes:> read "('a' ('b' 'c'))" :: SomeType Char ('a' ('b' 'c')) it :: SomeType Char
hope this helps
这篇关于如何在haskell中为数据类型创建Read的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文