What's the size of Int (bounded integer) in Haskell, or should I say in GHC?
As practice I wrote a short program to get the number of bits set in an Int
import Data.Bits
getBits :: Int -> Int
getBits x
| x == 0 = 0
| otherwise = 1 + (getBits y)
where y = x .&. (x - 1)
main = do
putStrLn "type a integer"
num <- getLine
let n = read num :: Int
putStrLn $ "result is: " ++ show (getBits n)
If I input number -1, the result is 64, which indicates the size of an Int is 64 bit. Why is that the case? Why it's not 32 bit as in C/C++?
The Int type is:
A fixed-precision integer type with at least the range [-2^29 .. 2^29-1]. The exact range for a given implementation can be determined by using minBound and maxBound from the Bounded class.
taken from the Haskell documentation.
You can use the types Int8 for 8bit ints, Int32 for 32 bit ints and Int64 for 64bit ints.
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With