haskell - Convert String to Int checking for overflow -
haskell - Convert String to Int checking for overflow -
when tried convert long integer int
, surprised no error thrown:
prelude> read "123456789012345678901234567890" :: int -4362896299872285998
readmaybe
text.read
module gives same result.
two questions:
which function should phone call perform safe conversion? how can type safe language on earth allow such unsafe things?update 1:
this effort write version of read
checks bounds:
{-# language scopedtypevariables #-} parseintegral :: forall . (integral a, bounded a) => string -> maybe parseintegral s = integertointegral (read s :: integer) integertointegral n | n < fromintegral (minbound :: a) = nil integertointegral n | n > fromintegral (maxbound :: a) = nil integertointegral n = $ frominteger n
is best can do?
background: why unchecked overflow wonderful
haskell 98 leaves overflow behavior explicitly unspecified, implementers , bad else. haskell 2010 discusses in 2 sections—in section inherited haskell 98, it's left explicitly unspecified, whereas in sections on data.int
, data.word
, specified. inconsistency resolved eventually.
ghc kind plenty specify explicitly:
all arithmetic performed modulo 2^n, n number of bits in type.
this extremely useful specification. in particular, guarantees int
, word
, int64
, word32
, etc., form rings, , principal ideal rings, under add-on , multiplication. means arithmetic work right—you can transform expressions , equations in lots of different ways without breaking things. throwing exceptions on overflow break these properties, making much more hard write , reason programs. times need careful when utilize comparing operators <
, compare
—fixed width integers not form ordered groups, these operators bit touchy.
reading integer involves many multiplications , additions. needs fast. checking create sure read "valid" not easy quickly. in particular, while it's easy find out whether add-on has overflowed, not easy find out whether multiplication has. sensible ways can think of perform checked read int
are
read integer
, check, convert. integer
arithmetic more expensive int
arithmetic. smaller things, int16
, read can done int
, checking int16
overflow, narrowed. cheaper, still not free.
compare number in decimal maxbound
(or, negative number, minbound
) while reading. seems more reasonably efficient, there still some cost. first section of reply explains, there nil inherently wrong overflow, it's not clear throwing error improve giving reply modulo 2^n.
haskell type-conversion
Comments
Post a Comment