Convert String to Int checking for overflow

后端 未结 2 1393
执念已碎
执念已碎 2021-01-20 03:04

When I tried to convert a very long integer to Int, I was surprised that no error was thrown:

Prelude> read \"123456789012345678901234567890\         


        
2条回答
  •  孤城傲影
    2021-01-20 03:45

    If isn't "unsafe", in that the behaviour of the problem isn't undefined. (It's perfectly defined, just probably not what you wanted.) For example, unsafeWriteAray is unsafe, in that if you make a mistake with it, it writes data into arbitrary memory locations, either causing your application to segfault, or merely making corrupt its own memory, causing it behave in arbitrary undefined ways.

    So much for splitting hairs. If you want to deal with such huge numbers, Integer is the only way to go. But you probably knew that already.

    As for why there's no overflow check... Sometimes you actually want a number to overflow. (E.g., you might convert to Word8 without explicitly ANDing out the bottom 8 bits.) At any rate, every possible arithmetic operation can potentially overflow (e.g., maxBound + 1 = minBound, and that's just normal addition.) Do you really want every single arithmetic operation to have an overflow check, slowing your program down at every step?

    You get the exact same behaviour in C, C++ or C#. I guess the difference is, in C# we have the checked keyword, which allows you to automatically check for overflow. Maybe somebody has a Haskell package for doing checked arithmetic… For now, it's probably simpler to just implement this one check yourself.

提交回复
热议问题