[Haskell-cafe] Derived Read instance for types with infix constructors (ghc 6.4.1)

Daniel Fischer daniel.is.fischer at web.de
Fri Aug 25 20:19:45 EDT 2006

Am Samstag, 26. August 2006 00:50 schrieb Misha Aizatulin:
> hi,
>   the Haskell Report 10.4 says that
> "The result of show is readable by read if all component types are
> readable"
>   however if I define a type like
> data T = A | T `And` T deriving (Read, Show)
>   then
> *Main> show $ A `And` A
> "A And A"
> *Main> (read "A And A") :: T
> *** Exception: Prelude.read: no parse
> *Main>
>   In fact, I wasn't able to guess, what I should type so that the value
> (A `And` A) gets parsed.

Appearance notwithstanding, your datatype introduces the _prefix_ constructor 
And (infix constructors are symbols beginning with a colon, like :+ etc).
And hugs and ghc 6.2.2 can read the prefix form:

ghc 6.2.2:
Ok, modules loaded: InfixR.
*InfixR> read "A `And` A" :: T
*** Exception: Prelude.read: no parse
*InfixR> read "And A A" :: T
And A A


InfixR> And A A
And A A
InfixR> A `And` A
And A A
InfixR> read "And A A" :: T
And A A
InfixR> read "A `And` A" :: T

Program error: Prelude.read: no parse

>   I have ghc 6.4.1. Looking into the code of the derived instance I see
> that it expects Text.Read.Lex.lex to return (Symbol "And") for the
> constructor. If I understand the code for lex correctly, then it parses
> things as Symbol if they consist only of
> "!@#$%&*+./<=>?\\^|:-~"
>   How then do I read values of type T defined above? Thanks in advance
> for any directions.

Put the constructor in the prefix position in the data definition and the 
derived Read instance of ghc 6.4.1 will also be able to read the prefix form.

> Cheers,
>   Misha


"In My Egotistical Opinion, most people's C programs should be
indented six feet downward and covered with dirt."
	-- Blair P. Houghton

More information about the Haskell-Cafe mailing list