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?
2 Answers
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
Comments
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
let x = 5 :: Intif you previously hadlet x = 5(which BTW is onlyIntegerbecause of the dreaded monomorphism restriction. If you:set -XNoMonomorphismRestriction, everything may work a charm without conversions).