Read instance of StdGen returns no parse

Yitzchak Gale gale at sefer.org
Sat Jan 26 19:01:22 EST 2008


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


More information about the Glasgow-haskell-users mailing list