[Haskell-beginners] Overflow when reading C types
Isaac Dupree
ml at isaac.cedarswampstudios.org
Mon Dec 2 23:14:20 UTC 2013
On 12/02/2013 05:09 PM, Michael Orlitzky wrote:
> On 12/02/2013 05:05 PM, Patrick Redmond wrote:
>> Yeah, the unsigned is to demonstrate how "-10" is being interpreted as a
>> number before being cast to an unsigned.
>>
>> My question is: Why isn't this just a read/parse error? "-10" isn't a
>> valid representation for any value of the CUInt type.
>>
>
> Sure it is,
>
> unsigned int x = -10;
>
> If you don't want a CUInt, don't use a CUInt =)
That is a C integral->integral conversion. A better comparison for
Haskell "read", if you think C gets to define the Haskell conversion
from Haskell string to C integral type, would be strtol()/strtoul(),
which are standard C functions that convert from C string to C integral
type.
strtol() saturates at LONG_MIN and LONG_MAX.
strtoul() saturates at ULONG_MAX and is modulo at 0 (the first time; if
the number is too negative then it saturates to ULONG_MAX).
Both set errno to ERANGE when they saturate.
C conversions from floating-point to signed or unsigned integral also
saturate.
Unsigned types being Z/nZ is mathematically sound, but C is not very
dedicated to this interpretation. Furthermore, C signed arithmetic is
undefined behavior if you overflow. Haskell is much more dedicated to
thinking both signed and unsigned C types are modulo than C is.
I too am curious whether it would make more sense for Haskell
read/readsPrec to fail to read out-of-range integers.
-Isaac
More information about the Beginners
mailing list