Primitive types and Prelude shenanigans
Wed, 21 Feb 2001 23:05:41 +1100
On 21-Feb-2001, Marcin 'Qrczak' Kowalczyk <[email protected]> wrote:
> Wed, 21 Feb 2001 12:55:37 +1100, Fergus Henderson <[email protected]> pisze:
> > The documentation in the Haskell report does not say what
> > `fromInteger' should do for `Int', but the Hugs behaviour definitely
> > seems preferable, IMHO.
> Sometimes yes. But for playing with Word8, Int8, CChar etc. it's
> sometimes needed to just cast bits without overflow checking, to
> convert between "signed bytes" and "unsigned bytes".
Both are desirable in different situations. But if you want to ignore
overflow, you should have to say so explicitly. `fromInteger' is
implicitly applied to literals, and implicit truncation is dangerous,
so `fromInteger' should not truncate.
There should be a different function for conversions that silently
truncate. You can implement such a function yourself, of course,
e.g. as follows:
trunc :: (Bounded a, Integral a) => Integer -> a
trunc x = res
where min, max, size, modulus, result :: Integer
min = toInteger (minBound `asTypeOf` res)
max = toInteger (maxBound `asTypeOf` res)
size = max - min + 1
modulus = x `mod` size
result = if modulus > max then modulus - size else modulus
res = fromInteger result
But it is probably worth including something like this in the standard
library, perhaps as a type class method.
Fergus Henderson <[email protected]> | "I have always known that the pursuit
| of excellence is a lethal habit"
WWW: <http://www.cs.mu.oz.au/~fjh> | -- the last words of T. S. Garp.