Int in Haskell uses the machines native precision. I know I can query the bounds using maxBound and minBound. Is there a similar way of querying the precision width?
Something like
getPrecision :: Int -> Int
which returns say either 32 or 64.
One possibility is
import Data.Bits
getPrecision = popCount (maxBound :: Int) + 1
The cleanest way, for recent libraries (the ones that ship with GHC 7.8 or later), is to use finiteBitSize
from Data.Bits
. This is exactly the function you requested. With earlier versions, you can use bitSize
, also from Data.Bits
, a non-total version of the same thing. Specifically, bitSize
will throw an exception if it's given something like Integer
that doesn't have a bit size. finiteBitSize
is in the FiniteBits
subclass, so applying it to an Integer
will give a type error. There's also a bitSizeMaybe
in recent libraries, but that seems generally less useful.
You could use sizeOf
but this comes with the caveat that the type must not have any padding bits.
import Foreign (Storable, sizeOf)
getPrecision :: Storable a => a -> Int
getPrecision dummy = sizeOf dummy * 8
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.