Numeric literals

Chris Angus
Tue, 28 Aug 2001 16:17:45 +0100

this is a bit ugly but would allow you to do 

if (x `isA` string) ...

or (x `isA` int) ...

int = int::Int
string = string::String

typeBind :: a -> ReadS a -> ReadS a
typeBind    _ x = x

isA :: Read a => String -> a -> Bool
isA s x = not (null (typeBind x (readsPrec 0) s))

-----Original Message-----
From: Simon Marlow []
Sent: 28 August 2001 15:53
To: Mark Carroll;
Subject: RE: Numeric literals

> 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?

In GHC, you can do this:

   import Exception

	do result <- catch (evaluate (read "foo" :: Int))
			       (\error -> ... )

but unfortunately read doesn't raise a useful exception (just error
" no parse"), so you can't filter it very easily.  However
I don't think that read is likely to raise any other exceptions.


Haskell-Cafe mailing list