
Hi All. in the function: func :: String -> Int func str = read str An absolute beginner as i am, want to use "read" to convert a String in a Int, but I don't know how to protect my function func from an exception when str is not a number like "12A". How can I do? Thanks in advance for any answer to this my simply question. Luca.

On Fri, Jan 15, 2010 at 07:49:40PM +0100, Luca Ciciriello wrote:
Hi All.
in the function:
func :: String -> Int func str = read str
An absolute beginner as i am, want to use "read" to convert a String in a Int, but I don't know how to protect my function func from an exception when str is not a number like "12A". How can I do?
Thanks in advance for any answer to this my simply question.
I have tried to solve this problem too, and I ended up using the function "reads", which gives you back information about the parse status. Hope this helps, iustin

Am Freitag 15 Januar 2010 19:49:40 schrieb Luca Ciciriello:
Hi All.
in the function:
func :: String -> Int func str = read str
An absolute beginner as i am, want to use "read" to convert a String in a Int, but I don't know how to protect my function func from an exception when str is not a number like "12A". How can I do?
Thanks in advance for any answer to this my simply question.
You can use the "reads" function, Prelude> :i reads reads :: (Read a) => ReadS a -- Defined in Text.Read Prelude> :i ReadS type ReadS a = String -> [(a, String)] -- Defined in Text.ParserCombinators.ReadP , which gives a list of pairs of (successful parse of start, remaining input), e.g. Prelude> reads "12A" :: [(Int,String)] [(12,"A")] Prelude> reads "12 " :: [(Int,String)] [(12," ")] to write your own safe conversion. Say readMaybe :: Read a => String -> Maybe a readMaybe str = case reads str of [(res,trail)] | all isSpace trail -> Just res _ -> Nothing You can work with that or use a default: readIntWithDefault0 :: String -> Int readIntWithDefault0 = maybe 0 id . readMaybe readWithDefault :: Read a => a -> String -> a readWithDefault d = maybe d id . readMaybe Whether supplying a default or using Maybe is the better option depends on the use-case.

An absolute beginner as i am, want to use "read" to convert a String in a Int, but I don't know how to protect my ? > >function func from an exception when str is not a number like "12A". How can I do?
Try reads instead. Something like readMaybe s = case reads s of [(i,"")] -> Just i _ -> Nothing Returns "Just" the value parsed in case all input is consumed and Nothing otherwise. A similar version can be made if partial parses are acceptable. Rahul
participants (4)
-
Daniel Fischer
-
Iustin Pop
-
Luca Ciciriello
-
Rahul Kapoor