James
James

Reputation: 161

How do I turn an Integer into an Int in Haskell

I want to turn an Integer into an Int so it agrees with my type declaration. There must be a simple way of doing this like casting in Java?

Upvotes: 0

Views: 325

Answers (2)

dflemstr
dflemstr

Reputation: 26167

Be aware that an Integer could have a value that is much larger than what fits in an Int, so you would get an overflow when doing the conversion in some cases.

However, with that precaution out of the way, the easiest way to do the conversion is to simply use the fromIntegral function:

myInteger :: Integer
myInteger = 1234

myInt :: Int
myInt = fromIntegral myInteger

Upvotes: 1

bheklilr
bheklilr

Reputation: 54078

Just use the fromInteger function:

fromInteger :: Num a => Integer -> a

You'd use it in GHCi like

> fromInteger (1 :: Integer) :: Int
1

But beware that there's some interesting behavior if you go beyond the bounds of an Int:

> let x = (fromIntegral (maxBound :: Int) :: Integer) + 1
> x
2147483648
> fromInteger x :: Int
-2147483648

Upvotes: 4

Related Questions