DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Legacy and Other Languages (http://www.daniweb.com/forums/forum42.html)
-   -   haskell - throwing an error on Read() (http://www.daniweb.com/forums/thread184605.html)

artemis_f Apr 1st, 2009 8:15 am
haskell - throwing an error on Read()
 
I know how to throw an error in Haskell however I don't know how to do it for the read function. When I do something like this:

-- find the number on the second line of file/second list of strings
getNo :: String->Int
getNo inputBigString = read((listOfLines inputBigString) !! 1)

I want to specify like if the line you are trying to convert to an integer is empty/ or you can't convert it to an Integer then let me specify what error message to specify. At the moment if I input a file where the second line is empty it says
"Program error: Prelude.read: no parse"
but I want to be able to specify what error message should be shown myself - how can I accomplish this?

Thanks

thoughtcoder Apr 1st, 2009 9:42 am
Re: haskell - throwing an error on Read()
 
Use reads.
> reads " 234 blah" :: [(Integer, String)]
[(234," blah")]
> reads "blah" :: [(Integer, String)]
[]
It returns a list of the different ways the desired thing can be parsed. For all standard types, this list is of length 1 or 0.

artemis_f Apr 2nd, 2009 1:53 am
Re: haskell - throwing an error on Read()
 
Ah thanks! That solves my difficulties!


All times are GMT -4. The time now is 2:48 pm.

Forum system based on vBulletin Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
©2003 - 2010 DaniWeb® LLC