[Haskell-beginners] using "read"
Daniel Fischer
daniel.is.fischer at web.de
Fri Jan 15 14:12:37 EST 2010
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.
More information about the Beginners
mailing list