I wrote a function in Haskell
toInt :: Float -> Int
toInt x = round $fromIntegral x
It is supposed to take in an Float and return the equivalent Int. I come from a C programming background, and in C, we could just cast it as an int.
However, in this case, I get the following compile error
No instance for (Integral Float)
arising from a use of `fromIntegral'
In the second argument of `($)', namely `fromIntegral x'
In the expression: round $ fromIntegral x
In an equation for `toInt': toInt x = round $ fromIntegral x
Any idea on how to fix this?
The workhorse for converting from integral types is fromIntegral , which will convert from any Integral type into any Num eric type (which includes Int , Integer , Rational , and Double ): fromIntegral :: (Num b, Integral a) => a -> b.
What's the difference between Integer and Int ? Integer can represent arbitrarily large integers, up to using all of the storage on your machine. Int can only represent integers in a finite range. The language standard only guarantees a range of -229 to (229 - 1).
fromIntegral :: (Integral a, Num b) => a -> b takes your Int (which is an instance of Integral ) and "makes" it a Num . sqrt :: (Floating a) => a -> a expects a Floating , and Floating inherit from Fractional , which inherits from Num , so you can safely pass to sqrt the result of fromIntegral.
Your type annotation specifies that x
should be a Float
, which means it can't be a parameter to fromIntegral
since that function takes an Integral.
You could instead just pass x
to round
:
toInt :: Float -> Int
toInt x = round x
which in turn can be slimmed down to:
toInt :: Float -> Int
toInt = round
which implies that you may be better off just using round
to begin with, unless you have some specialized way of rounding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With