Read instance of StdGen returns no parse

Hi all, According to http://haskell.org/ghc/docs/latest/html/libraries/random/System-Random.html#... the Read StdGen instance should never fail. However, in GHC 6.8.2, it appears to:
ghci GHCi, version 6.8.2: http://www.haskell.org/ghc/ :? for help Loading package base ... linking ... done. Prelude> :m System.Random Prelude System.Random> read "exsqueeze me" :: StdGen Loading package old-locale-1.0.0.0 ... linking ... done. Loading package old-time-1.0.0.0 ... linking ... done. Loading package random-1.0.0.0 ... linking ... done. *** Exception: Prelude.read: no parse Prelude System.Random> Leaving GHCi.
It first fails for me on strings of length seven. Is this a bug, or have I done something wrong? -- Denis

Denis Bueno wrote:
the Read StdGen instance should never fail. However, in GHC 6.8.2, it appears to: It first fails for me on strings of length seven.
You need to use "fst . head . reads" instead of "read". The Read instance of StdGen only uses part of the string, and politely gives you back the unused portion so that you can use it for something else. But the side effect of that is that you can only use "reads", not "read". Using "read" means that you guarantee that the entire string you supply will be consumed by the parser. When you supply an arbitrary string to the parser for StdGen - i.e., not one produced by the Show instance - there isn't any way for you ever to guarantee that, because the exact amount of the string that will be needed is an internal implementation detail. (Whereas the use of "head" with "reads" is safe, because there is guaranteed to be some parse.) The documentation in System.Random is a bit misleading. It says "the read instance of StdGen has the following properties: It guarantees to succeed on any string..." The word "read" should really be "Read" instead. It also wouldn't hurt to mention that the read *function* may fail, so use reads instead. Hope this helps. -Yitz

On Jan 26, 2008 7:01 PM, Yitzchak Gale
The documentation in System.Random is a bit misleading. It says "the read instance of StdGen has the following properties: It guarantees to succeed on any string..." The word "read" should really be "Read" instead. It also wouldn't hurt to mention that the read *function* may fail, so use reads instead.
Hope this helps.
Definitely. The error now makes sense. Thanks for the response. -- Denis
participants (2)
-
Denis Bueno
-
Yitzchak Gale