Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Int size

Tags:

haskell

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++?

like image 954
swang Avatar asked Sep 15 '26 06:09

swang


1 Answers

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

like image 127
Oscar Robinson Avatar answered Sep 18 '26 12:09

Oscar Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!