Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from Float to Int in Haskell

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?

like image 416
Sajid Anower Avatar asked Mar 23 '17 11:03

Sajid Anower


People also ask

What does fromIntegral do in Haskell?

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 is the difference between int and Integer in Haskell?

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).

How do you find the square root in Haskell?

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.


1 Answers

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.

like image 155
Chad Gilbert Avatar answered Oct 13 '22 16:10

Chad Gilbert