[Haskell-cafe] How to "Read" this?

Gwern Branwen gwern0 at gmail.com
Tue Jul 14 20:41:21 EDT 2009


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512

On Tue, Jul 14, 2009 at 1:49 AM, Magicloud Magiclouds wrote:
> Hi,
>  I have a data structure, which shows like this: AttrBgColor {bgColor
> = Color 0 0 0}
>  And the following is my Read code. But it failed parsing....
>  31 instance Read Attribute where
>  32   readsPrec _ str = [ (mkAttr attr_ color, rest) | (attr_, rest1)   33                                                  , (color, rest)
>   34
>   || (isPrefixOf " {fgColor = " rest1)
>  35
>   then case reads $ drop 12 rest1 of
>  36
>          [(color_, rest_)] -> [(color_, rest_)]
>  37
>          _ -> [(Color 0 0 0, rest1)]
>  38
>   else [(Color 0 0 0, rest1)] ]
>  39     where mkAttr "AttrFgColor" color = AttrFgColor color
>  40           mkAttr "AttrBgColor" color = AttrBgColor color
>  41           mkAttr "AttrInverse" _ = AttrInverse
>  42           mkAttr "AttrWeak" _ = AttrWeak
>  43           mkAttr "AttrUnderline" _ = AttrUnderline

Perhaps I am mis-understanding you, but why aren't you just deriving
Read & Show?
eg. data AttrBgColor = AttrBgColor { bgColor :: Color Int Int Int }
deriving (Read, Show)

It would certainly seem to be much easier and more reliable than
hand-rolling an ad hoc parser.

- --
gwern
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEAREKAAYFAkpdJS8ACgkQvpDo5Pfl1oI/1QCfUgfHVsD/PMmgS6Z1sMMPljWt
zOkAn0hQ3GBLFxHCO6ryoYyvPZ+nDJdp
=qR5d
-----END PGP SIGNATURE-----


More information about the Haskell-Cafe mailing list