Numeric literals

[email protected] [email protected]
28 Aug 2001 12:55:01 -0000


Mark Carroll <[email protected]> wrote: 
> I also haven't yet worked out how to tell if a string is "read"able or
> not, yet - if (read "45")::Integer or whatever gives an error (e.g. if I'd
> put "af" instead of "45"), it seems to be pretty uncatchable, which is a
> pain. How do I tell if an instance of reading will work, or catch that it 
> didn't?

You need to resort to

reads :: Read a => ReadS a

where ReadS is a typical parser type constructor
(``replacing failure by a list of successes'', see BibTeX entry below),
defined in the prelude:

type ReadS a = String -> [(a,String)]


You might want to wrap it in something like the following:

read' :: Read a => String -> Maybe a
read' s = case reads s of
            ((a,[]):_) -> Just a
            _          -> Nothing


For understanding the machinery it is useful to look at the
class and instance definitions for Read in the Prelude.


Wolfram

=========================================================


@InProceedings{Wadler-1985a,
  author =       "Philip Wadler",
  title =        "How to Replace Failure by a List of Successes --- {A}
                 Method for Exception Handling, Backtracking, and
                 Pattern Matching in Lazy Functional Languages",
  booktitle =    {Proceedings of the Second Conference on Functional
                 Programming Languages and Computer Architecture},
  confaddress =  "Nancy, France",
  publisher =    Springer,
  series =       LNCS,
  confdate =     SEP # " 16--19,",
  year =         "1985",
  pages =        "113--128",
}