[Haskell-beginners] Data.Text to Int?

Daniel Fischer daniel.is.fischer at googlemail.com
Fri Dec 14 18:25:23 CET 2012


On Freitag, 14. Dezember 2012, 16:19:02, Emmanuel Touzery wrote:
> I see... However it uses Either and returns a pair, unlike "read". It's
> a plus for reliability but an annoyance in my case. In my case I know
> positively it's a number.
> In this case I did a filter isDigit, but this will happen also if I
> match using a regular expression and [0-9] or \d.
> 
> In the end the most terse way to code it is to go through unpack then it
> seems.
> Using Data.Text.Read all I see is:
> 
> fst $ right $ decimal t
> where right (Right a) = a
> 
> so I'll probably do:
> 
> read $ unpack t
> 
> and be done with it...

Note that unpacking to String and then reading from the String is not the most 
efficient way.

For the cases you are sure to have a valid input Text and no leftovers (you 
are interested in), you can define

it'sSafeIPromise :: Reader a -> Text -> a
it'sSafeIPromise = (value .)
  where
    value (Right (v,_)) = v

and use

readInt :: Text -> Int
readInt = it'sSafeIPromise decimal

If you use it a lot, it's worth the bit of additional typing.



More information about the Beginners mailing list