1

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?

1
  • You don't "turn" objects of one type into another one, at best you convert between types. But in Haskell, it's generally preferred to simply work with the required type right from the beginning; thanks to polymorphic return types etc. this often works without even thinking about it. In ghci, you might just use let x = 5 :: Int if you previously had let x = 5 (which BTW is only Integer because of the dreaded monomorphism restriction. If you :set -XNoMonomorphismRestriction, everything may work a charm without conversions). Commented Nov 17, 2013 at 17:29

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.